dpzff20644 2018-09-11 08:08
浏览 29
已采纳

PHP和魔术方法进入自己的类

my code:

class Test {

    private $a = 5;

    public function __set($name, $value)
    {
        // TODO: Implement __set() method.
        echo $name . "#" .$value."<br>";
    }

    public static function do_test(){
        $x= new Test();
        $x->a=5;
    }


}
$x=new Test();
$x->a=3;
Test::do_test();

output:

a#3

The function static do_test() doesn't call the magic methods (__set). Why? Thank you!

  • 写回答

1条回答 默认 最新

  • duan1979768678 2018-09-11 08:18
    关注

    Magic methods are only invoked when the property is inaccessible (including if it doesn't exist). Your property is private. Test::do_test has access to that private property, because you're accessing it from a context with the same class. It doesn't have to be the same instance (i.e. $this or self), it just needs to be the same class context. A class can access its private properties even if it's not the same instance. So your magic method is not needed for that access.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?