我看到了一些类似于下面的代码,奇怪的是,__get
方法被调用了两次,为什么?
class Foo {
private $bar;
function __get($name){
echo "__get is called!";
return $this->$name;
}
function __unset($name){
unset($this->$name);
}
}
$foo = new Foo;
unset($foo->bar);
echo $foo->bar;
注意:unset($foo->bar)
不会调用__get
。
发布于 2011-09-27 02:40:17
对我来说,它就像一只虫子。输入一些调试代码(如下所示),并查看结果:
<?php
class Foo {
private $bar;
function __get($name){
echo "__get(".$name.") is called!\n";
debug_print_backtrace();
$x = $this->$name;
return $x;
}
function __unset($name){
unset($this->$name);
echo "Value of ". $name ." After unsetting is \n";
echo $this->$name;
echo "\n";
}
}
echo "Before\n";
$foo = new Foo;
echo "After1\n";
unset($foo->bar);
echo "After2\n";
echo $foo->bar;
echo "After3\n";
echo $foo->not_found;
?>
结果是:
Before
After1
Value of bar After unsetting is
__get(bar) is called!
#0 Foo->__get(bar) called at [E:\temp\t1.php:17]
#1 Foo->__unset(bar) called at [E:\temp\t1.php:24]
PHP Notice: Undefined property: Foo::$bar in E:\temp\t1.php on line 9
After2
__get(bar) is called!
#0 Foo->__get(bar) called at [E:\temp\t1.php:26]
__get(bar) is called!
#0 Foo->__get(bar) called at [E:\temp\t1.php:9]
#1 Foo->__get(bar) called at [E:\temp\t1.php:26]
PHP Notice: Undefined property: Foo::$bar in E:\temp\t1.php on line 9
After3
__get(not_found) is called!
#0 Foo->__get(not_found) called at [E:\temp\t1.php:28]
PHP Notice: Undefined property: Foo::$not_found in E:\temp\t1.php on line 9
发布于 2011-09-27 02:47:51
被调用
1)
return $this->$name;
2)
echo $foo->bar;
在守则中:
class Foo {
private $bar;
function __get($name){
echo "__get is called!";
return $this->$name; *** here ***
}
function __unset($name){
unset($this->$name);
}
}
$foo = new Foo;
unset($foo->bar);
echo $foo->bar; *** and here ***
__get()用于从无法访问的属性中读取数据。
因此,不设置变量,转$foo->bar和$this->bar不可访问.但是,如果取消了unset,则$foo->bar是不可访问的,但是$this->bar是可访问的。
但是,我不知道PHP如何避免递归调用函数。可能是PHP很聪明,或者变量在某个时候是自设置的。
发布于 2011-09-27 02:28:19
每次尝试访问变量时都会调用神奇的__get函数。如果您查看您的代码,就会精确地执行两次。一次在unset函数中,一次在echo函数中。
unset($foo->bar);
回声$foo->bar;
https://stackoverflow.com/questions/7567603
复制