天梯梦 发表于 2013-2-7 00:17:40

__call、__set 和 __get的用法

__call的用法
 
PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在的方法,__call 方法将会被自动调用。
 
例:__call
 

<?phpclass foo {function __call($name,$arguments) {print("Did you call me? I'm $name!<br>");print_r($arguments);print("<br><br>");}function doSecond($arguments){print("Right, $arguments!<br>");}}$test = new foo();$test->doFirst('no this function');$test->doSecond('this function exist');?>  
__call 实现“过载”动作
 
 这个特殊的方法可以被用来实现“过载(overloading)”的动作,这样你就可以检查你的参数并且通过调用一个私有的方法来传递参数。
 
例:使用 __call 实现“过载”动作
 

<?phpclass Magic {function __call($name,$arguments) {if($name=='foo') {if(is_int($arguments)) $this->foo_for_int($arguments);if(is_string($arguments)) $this->foo_for_string($arguments);}}   private function foo_for_int($x) {print("oh an int!");}   private function foo_for_string($x) {print("oh a string!");}} $test = new Magic();$test->foo(3);$test->foo("3");?>  
 __set 和 __get的用法
 
这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。
 
例: __set 和 __get
 

<?phpclass foo {function __set($name,$val) {print("Hello, you tried to put $val in $name<br>");} function __get($name) {print("Hey you asked for $name<br>");}}$test = new foo();$test->__set('name','justcoding');$test->__get('name');?>  
 
 
 
 
 
 
页: [1]
查看完整版本: __call、__set 和 __get的用法