【发布时间】: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