方法调用和成员访问都能通过__call,__get和__set方法被加载。这些方法将只有当你试图访问不包括成员或方法的对象或继承对象时触发。不是所有的重载方法都必须被定义为static. 从PHP 5.1.0开始也可以通过__isset()和__unset()方法逐个重载isset()和unset()函数。 成员函数重载(Member overloading) void __set ( string name, mixed value ) mixed __get ( string name ) bool __isset ( string name ) void __unset ( string name ) 类成员可以通过定义这些指定的特定方法加载类中的自定义代码。$name参数被用来命名变量,这些变量必须是被设置的或返回的。__set()方法的$value参数指定设置$name的对象的值。 例子 19-18.使用__get,__set,__isset和__unset重载的例子
PHP代码如下: [复制到剪切板] CODE: <?php class Setter { public $n; private $x = array("a" => 1, "b" => 2, "c" => 3); private function __get($nm) { echo "Getting [$nm]/n"; if (isset($this->x[$nm])) { $r = $this->x[$nm]; print "Returning: $r/n"; return $r; } else { echo "Nothing!/n"; } } private function __set($nm, $val) { echo "Setting [$nm] to $val/n"; if (isset($this->x[$nm])) { $this->x[$nm] = $val; echo "OK!/n"; } else { echo "Not OK!/n"; } } private function __isset($nm) { echo "Checking if $nm is set/n"; return isset($this->x[$nm]); } private function __unset($nm) { echo "Unsetting $nm/n"; unset($this->x[$nm]); } } $foo = new Setter(); $foo->n = 1; $foo->a = 100; $foo->a++; $foo->z++; var_dump(isset($foo->a)); //true unset($foo->a); var_dump(isset($foo->a)); //false // this doesn't pass through the __isset() method because 'n' is a public property var_dump(isset($foo->n)); var_dump($foo); ?>
上例将输出:
Setting [a] to 100 OK! Getting [a] Returning: 100 Setting [a] to 101 OK! Getting [z] Nothing! Setting [z] to 1 Not OK! Checking if a is set bool(true) Unsetting a Checking if a is set bool(false) bool(true) object(Setter)#1 (2) { ["n"]=>int(1)["x:private"]=>array(2) { ["b"]=> int(2) ["c"]=> int(3) } }