使用ReflectionClass的受保护的变量

时间:2013-01-17 23:05:53

标签: php reflection

我正在尝试通过被叫类读取受保护的变量。我的受保护的$ test和新的ReflectionClass的问题在哪里?

<?PHP
class foo
{
    protected $test = ['foo' => 'foo'];
    public function __construct()
    {
        $class = get_called_class();

        do
        {
            foreach((new \ReflectionClass($class))->getDefaultProperties() as $property => $value)
                var_dump([$class.'::'.$property => $value]);
        }
        while($class = get_parent_class($class));
    }
}

class baz extends foo
{
    protected $test = ['baz' => 'baz'];
}

new baz;

实际:

  ["baz::test"]=>
    ["baz"]=> "baz"
  ["foo::test"]=>
    ["baz"]=> "baz"

预期:

  ["baz::test"]=>
    ["baz"]=> "baz"
  ["foo::test"]=>
    ["foo"]=> "foo"

亲切的问候。

1 个答案:

答案 0 :(得分:0)

没有问题。父类中的$test类变量设置为:

array
(
   'foo' => 'foo'
)

继承它的子类将覆盖数组的值(它不会添加到数组中,而是替换所有现有的键/值):

array
(
   'baz' => 'baz'
)
相关问题