加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php没有在静态函数内重载

发布时间:2020-12-13 17:21:05 所属栏目:PHP教程 来源:网络整理
导读:我似乎不明白为什么下面的代码只打
我似乎不明白为什么下面的代码只打印“TEST”两次.

<?php

class A {
    private $test = "TEST<br />";

    public static function getInstance() {
        return new self();
    }

    public static function someStaticMethod() {
        $a = new self();
        $a->test;
    }

    public function __get($args) {
        echo $this->$args;
    }
}

/* echo's "TEST" */
$a = new A();
$a->test;

/* echo's "TEST" */
$a2 = A::getInstance();
$a2->test;

/*
No output... eeerhm... how come?
Why is $a->test (inside someStaticMethod()) not being overloaded by __get ??
*/
A::someStaticMethod();

?>

PHP网站说(link):

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods should not be declared static. As of PHP 5.3.0,a warning is issued if one of the magic overloading methods is declared static.

但我认为他们试图说你应该宣布魔术方法是静态的.例如.:

public static function __get(){}

事实上,我实际上是在对象上下文中使用它. $a = new self();返回变量$a中A类的实例.然后我使用$a-> test(对象上下文imo?)来获取私有的“test”变量,而该变量又应该被重载…

我很迷惑…

解决方法

看来,在A :: someStaticMethod的上下文中,PHP允许您直接访问私有变量$test,因此魔术方法不会执行.如果你回复$a-> test;从那里,你会看到它被访问.

根据PHP Manual,这是预期的行为:

Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读