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.

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

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料