<?php class Magic{ public function __tostring(){ return "hello world!"; } } $obj = new Magic(); echo $obj;//hello world! ?>
__invoke():当对象被当成方法调用时,这个方法会被自动调用。
<?php class Magic{ public function __tostring(){ return "hello world!"; } public function __invoke($x){ echo "__invoke called with param ".$x."\n"; } } $obj = new Magic(); $obj(10);//__invoke called with param 10 ?>
<?php class Magic{ //`$name` 参数是要调用的方法名称。`$arguments` 参数是一个枚举数组, //包含着要传递给方法 `$name` 的参数。 public function __call($name,$arguments){ //implode() 函数把数组元素组合为一个字符串。implode(separator,array) echo "Calling " . $name ." with param: ".implode(", ",$arguments)."\n"; } } $obj = new Magic(); $obj->run("para1","para2");//obj去调用run方法,输出:Calling run with param: para1, para2 ?>
__get()和__set()
在给不可访问属性赋值时,__set()会被调用 读取不可访问属性的值时,__get()会被调用
<?php class Magic{ //function 前要有static关键字 public function __get($name){ return "Getting the property " . $name; } } $obj = new Magic(); echo $obj->className."\n";//Getting the property className ?>
读取不可访问属性的值时,__get()会被调用
<?php class Magic{
public function __set($name,$value){ echo "Setting the property " . $name ."to value ". $value ."\n"; } } $obj = new Magic(); $obj->className = 'MagicClass';//Setting the property classNameto value MagicClass ?>
<?php class Magic{ public function __isset($name){ echo "__isset invoked\n"; return true; } } $obj = new Magic(); echo '$obj->className is set?'.isset($obj->className)."\n";//__isset invoked $obj->className is set?1 ?>