代码如下:
<?php class MagicTest{ public function __tostring(){ return "This is the Class MagicTest. "; } public function __invoke($x){ echo "__invoke called with parameter ".$x."\n"; } //方法的重载 //这个方法的参数第一个就是调用的方法的名称,第二个参数是方法调用的参数组成的数组 public function __call($name,$arguments){ echo "Calling " . $name . "with parameters: ". implode(",", $arguments)."\n"; } //静态方法的重载,注意这个方法需要设定为static public static function __callStatic($name,$arguments){ echo "Static Calling " . $name . "with parameters: ". implode(",", $arguments)."\n"; } public function __get($name){ return "Getting the property ".$name."\n"; } public function __set($name, $value){ return "Setting the property ".$name."to value" . $value."\n"; } } $obj = new MagicTest(); echo $obj->className."\n"; //className未定义,但是通过魔术方法__get,这个方法好像被定义了一样 $obj->className='MagicClassX'; ?>
为啥我的__set魔术方法不起作用,只output
Getting the property className 然后直接跟着MagicClassX
因为是echo而非return
public function __set($name, $value){
return "Setting the property ".$name."to value" . $value."\n";
}
你返回的是一个$obj->className赋值,而不是直接在该__set魔术方法输出