我正在使用Reflection来调整对象中的各种值,并且我有一个我需要调整的父对象。
例如:
class Ford extends Car
{
private $model;
}
class Car
{
private $color;
}
我可以轻松地使用Reflection来更改模型,但是如何将父项与子项分开,以便我可以在父项上使用Reflection?
一些伪代码,我希望是可能的:
$ford = new Ford();
$manipulator = new Manipulator($ford);
$manipulator->set('model','F-150');
$manipulator->setParentValue('color','red');
class Manipulator
{
public function __construct($class) {
$this->class = $class;
$this->reflection = new \ReflectionClass($class);
}
public function set($property,$value) {
$property = $this->reflection->getProperty($property);
$property->setAccessible(true);
$property->setValue($this->class,$value);
}
public function setParentValue() {
$parent = $this->reflection->getParent();
$property = $this->reflection->getProperty($property);
$property->setAccessible(true);
// HOW DO I DO THIS?
$property->setValue($this->class::parent,$value);
}
}
问题的要点:
在这种情况下,如何从对象外部更改$ color?
有没有像Ford :: parent()或get_parent_object($ ford)这样的东西?
注意
上面使用的对象不是确切的场景,但仅用于说明概念。在现实世界的情况下,我有一个父/子关系,我需要能够从外部访问/更改每个中的值。
回答
请检查下面的答案......我想通了。
经过广泛的审查,我发现我无法访问对象本身之外的对象的父对象作为对象。
但是,使用Reflections,我能够解决上面发布的示例:
<?php
class Car
{
private $color;
public function __construct()
{
$this->color = 'red';
}
public function color()
{
return $this->color;
}
}
class Ford extends Car
{
}
$ford = new Ford();
echo $ford->color(); // OUTPUTS 'red'
$reflection = new ReflectionClass($ford);
$properties = $reflection->getProperties();
foreach($properties as $property) {
echo $property->getName()."\n>";
}
$parent = $reflection->getParentClass();
$color = $parent->getProperty('color');
$color->setAccessible(true);
$color->setValue($ford,'blue');
echo $ford->color(); // OUTPUTS 'blue'
请参阅get_parent_class():http://php.net/manual/en/function.get-parent-class.php
function getPrivateProperty(\ReflectionClass $class, $property)
{
if ($class->hasProperty($property)) {
return $class->getProperty($property);
}
if ($parent = $class->getParentClass()) {
return getPrivateProperty($parent, $property);
}
return null;
}
这是函数I answered your other question的静态版本:
function getProperties($object) {
$properties = array();
try {
$rc = new \ReflectionClass($object);
do {
$rp = array();
/* @var $p \ReflectionProperty */
foreach ($rc->getProperties() as $p) {
$p->setAccessible(true);
$rp[$p->getName()] = $p->getValue($object);
}
$properties = array_merge($rp, $properties);
} while ($rc = $rc->getParentClass());
} catch (\ReflectionException $e) { }
return $properties;
}