【问题标题】:Inconsistencies in looping through the private properties of a subclass循环遍历子类的私有属性的不一致
【发布时间】:2015-03-05 12:59:48
【问题描述】:

我试图遍历一个类的私有属性。执行此循环的方法包含在父类中。考虑以下代码:

class ChildClass extends ParentClass {
    private $childProp = "childPropValue";
}

class ParentClass {
    private $parentProp = "parentPropValue";

    public function PrintProperties()
    {
        echo "--- print_r(\$this) ---\n";
        print_r($this);

        echo "\n\n--- foreach(\$this) ---\n";
        foreach($this as $propKey => $propValue) {
            print_r($propKey . ":");
            print_r($propValue . "\n");
        }

        echo "\n\n--- reflection->getProperties ---\n";
        $refl = new \ReflectionClass($this);
        print_r($refl->getProperties());
    }
}

$child = new ChildClass();
$child->PrintProperties();

这个输出:

--- print_r($this) ---
ChildClass Object
(
    [childProp:ChildClass:private] => childPropValue
    [parentProp:ParentClass:private] => parentPropValue
)


--- foreach($this) ---
parentProp:parentPropValue


--- reflection->getProperties ---
Array
(
    [0] => ReflectionProperty Object
        (
            [name] => childProp
            [class] => ChildClass
        )

)

print_r($this) 正确地将 $this 识别为 ChildClass 对象,然后列出该对象的 2 个私有属性并列出该属性的 2 个对应类。可以说 print_r 仅用于调试目的,因此打印这两个属性在这方面都很有用。

现在,foreach($this) 循环使用与 print_r 相同的变量,但这里只列出了 parentProp。此行为可能很直观,因为此构造用于循环访问可访问的属性。

然而,反射方法的打印结果正好相反,只列出了在此范围内无法访问的“childProp”。这是因为类名是 ChildClass 并且反射使用该名称来确定属性而产生不同结果的事实吗?

我想我在这里回答了我自己的问题,但仍然想知道其他人对此事的看法。

【问题讨论】:

    标签: php reflection


    【解决方案1】:

    第二个选项,foreach,只能看到公共和受保护的值,就像你说的,但我认为 \ReflectionClass 默认使用过滤器 ALL。

    我认为您在 ChildClass 中看不到父私有属性,您需要创建一个构造/gettter 以进行访问或将 $parentProp 更改为受保护。

    print_r($this) -> 我认为任何隐私限制都是显而易见的,所以请查看全部

    foreach($this) -> 我认为 $this 只接受 parentClass 可访问的键值,这是它的创建位置,并且只能访问 parentClass 的变量

    ReflectionProperty -> 我认为创建一个 Children 类并且无法访问 parentClass 的私有属性

    对不起我的英语不好^^U

    【讨论】:

      猜你喜欢
      • 2012-07-05
      • 1970-01-01
      • 2023-01-11
      • 2015-08-09
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多