__get(),__set(),__isset(),__unset()
__get(),__set(),__isset(),__unset()
在给不可访问属性赋值时,__set()会被调用
读取不可访问属性的值时,__get()会被调用
当对不可访问属性调用isset()或empty()时,__isset()会被调用
当对不可访问属性调用unset()时,__unset()会被调用
所谓不可访问属性,实际上就是在调用某个属性时发现这个属性没有被定义,这时候不同的操纵会触发不同的魔术方法
这几个方法也被称为属性重载的魔术方法
1 <?php 2 class MagicTest{ 3 public function __get($name) { 4 return "Getting the property ".$name."<br/>"; 5 } 6 public function __set($name,$value) { 7 echo "setting the property ".$name." to value ".$value."<br/>"; 8 } 9 public function __isset($name) { 10 echo "__isset invoke"."<br/>"; 11 return true; 12 } 13 public function __unset($name) { 14 echo "unsetting property ".$name; 15 } 16 } 17 18 $obj = new MagicTest(); 19 echo $obj->classname; 20 $obj->className="MagicClassX"; 21 echo '$obj->ClassName is set?'.isset($obj->className)."<br/>"; 22 echo '$obj->className is empty?'.empty($obj->className)."<br/>"; 23 unset($obj->className);
输出为:
Getting the property classname setting the property className to value MagicClassX __isset invoke $obj->ClassName is set?1 __isset invoke $obj->className is empty? unsetting property className