duanhua9398 2011-09-27 10:23
浏览 16
已采纳

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

I have seen some code like below, and it is strange that the __get method has been called twice, why?

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;

Attention: unset($foo->bar) will not call the __get.

  • 写回答

3条回答 默认 最新

  • duagfgfn1981 2011-09-27 10:40
    关注

    For me, it looks like a bug. Put some debugging code (the following) and see the result:

    <?php
    
    class Foo {
        private $bar;
    
        function __get($name){
            echo "__get(".$name.") is called!
    ";
            debug_print_backtrace();
            $x = $this->$name;
            return $x;
        }
    
        function __unset($name){
            unset($this->$name);
    
            echo "Value of ". $name ." After unsetting is 
    ";
            echo $this->$name;
            echo  "
    ";
        }
    }
    echo "Before
    ";
    $foo = new Foo;
    echo "After1
    ";
    unset($foo->bar);
    echo "After2
    ";
    echo $foo->bar;
    echo "After3
    ";
    echo $foo->not_found;
    ?>
    

    The result is:

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作