循环子类的私有属性时存在不一致


Inconsistencies in looping through the private properties of a subclass

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

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",而该"childProp"在此范围内是不可访问的。这是否会产生不同的结果,因为类名是ChildClass,而反射使用该名称来确定属性?

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

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

我认为,您在ChildClass中看不到父级私有属性,您需要创建一个用于访问的construct/getter,或者将$parentProp更改为protected。

print_r($this)->我认为任何明显的隐私限制,所以请查看所有

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

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

抱歉我的英语不好^^U