gpt4 book ai didi

php - 为什么魔术方法 '__get' 被调用了两次?

转载 作者:搜寻专家 更新时间:2023-10-31 20:51:03 25 4
gpt4 key购买 nike

我看过如下代码,很奇怪__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

最佳答案

对我来说,它看起来像一个错误。放一些调试代码(如下)并查看结果:

<?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

关于php - 为什么魔术方法 '__get' 被调用了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7567603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com