Php 子类私有属性循环中的不一致性
我试图循环一个类的私有属性。执行此循环的方法包含在父类中。考虑下面的代码:Php 子类私有属性循环中的不一致性,php,reflection,Php,Reflection,我试图循环一个类的私有属性。执行此循环的方法包含在父类中。考虑下面的代码: class ChildClass extends ParentClass { private $childProp = "childPropValue"; } class ParentClass { private $parentProp = "parentPropValue"; public function PrintProperties() { echo "---
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而产生不同的结果,而反射使用该名称来确定属性
我想我在这里回答了我自己的问题,但还是想知道其他人对这件事的看法。第二个选项foreach只能看到公共和受保护的值,如您所说,但我认为\ReflectionClass默认情况下使用filter ALL 我认为,在ChildClass中看不到父私有属性,您需要创建一个用于访问的构造/getter,或者将$parentProp更改为protected 打印($this)->我认为任何隐私限制都是显而易见的,所以请查看所有内容 foreach($this)->我认为,在$this中只接受父类可访问的键值,它是在这里创建的,并且只能访问父类的变量 ReflectionProperty->我想创建一个Children类,不能访问parentClass的私有属性 对不起,我的英语不好