PHP 魔术 __get 不适用于抽象基础中的变量 class

PHP magic __get not working for variable in abstract base class

在我的项目中,我经常使用 class 继承。 现在我注意到,当我想访问基 class 中的变量时,我的魔法 getter 没有触发。 因此以下代码:

abstract class A
{
    protected $varA;

    final public function __get($var)
    {
        echo $var;
    }
}

class B extends A
{
    protected $varB;
}

class C extends A
{
    public function test()
    {
        $test = new B();
        $test->varB; // Get output
        $test->varA; // No output
    }
}

$test = new C();
$test->test();

__get 仅在 属性 不存在时触发 .

varA 是您的一个 属性 对象。唯一的问题是它受到保护。因此无法从 class.

外部访问

来自 CHILD class 受保护的变量可用。 Child class 看到 varA,但 varA 为空

现在我看到您遇到了 php 功能。属性的可见性依赖于 类 但不依赖于对象。

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.

http://php.net/manual/en/language.oop5.visibility.php#example-208

$varA 是 ClassA 的受保护变量。

Class B 和 C 是 Class A 的扩展。

所以 $varA 存在于 C 或 B 的实例中,因为受保护的变量在它们定义的 class 的子代中是可访问和可赋值的。这就是它们的用途。

因为$varA存在,所以__get没有被触发。

我不确定您希望有什么不同?