问题描述
我正在尝试通过反射访问/更改类的父级的属性.
I am trying to access/change the properties of a class' Parent through Reflection.
如果我在子进程上运行 ReflectionClass::getProperties(),它是否也返回父进程拥有的任何属性?
If I run ReflectionClass::getProperties() on the child, does it also return any properties that the Parent has as well?
如果没有,有没有办法使用反射访问父属性?
If it doesn't, is there any way to access the parent properties using Reflection?
推荐答案
我完成了这个快速测试.当您获取子类的属性时,看起来父类的私有属性是隐藏的.但是,如果您调用 getParentClass()
然后 getProperties()
您将拥有缺少的一组私有道具.
I worked up this quick test. It looks like private properties of the parent are hidden when you get the child classes's properties. However, if you invoke getParentClass()
then getProperties()
you will have the missing set of private props.
<?php
class Ford {
private $model;
protected $foo;
public $bar;
}
class Car extends Ford {
private $year;
}
$class = new ReflectionClass('Car');
var_dump($class->getProperties()); // First chunk of output
var_dump($class->getParentClass()->getProperties()); // Second chunk
输出(注意私有属性 Ford::model
丢失):
Output (notice the private prop Ford::model
is missing):
array(3) {
[0]=>
&object(ReflectionProperty)#2 (2) {
["name"]=>
string(4) "year"
["class"]=>
string(3) "Car"
}
[1]=>
&object(ReflectionProperty)#3 (2) {
["name"]=>
string(3) "foo"
["class"]=>
string(4) "Ford"
}
[2]=>
&object(ReflectionProperty)#4 (2) {
["name"]=>
string(3) "bar"
["class"]=>
string(4) "Ford"
}
}
Second Chunk(包含福特类的所有属性):
Second Chunk (contains all the properties of the Ford class):
array(3) {
[0]=>
&object(ReflectionProperty)#3 (2) {
["name"]=>
string(5) "model"
["class"]=>
string(4) "Ford"
}
[1]=>
&object(ReflectionProperty)#2 (2) {
["name"]=>
string(3) "foo"
["class"]=>
string(4) "Ford"
}
[2]=>
&object(ReflectionProperty)#5 (2) {
["name"]=>
string(3) "bar"
["class"]=>
string(4) "Ford"
}
}
这篇关于ReflectionClass::getProperties() 是否也获取父级的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!