johnnietheblack johnnietheblack - 1 month ago 6
PHP Question

How to get the parent object in PHP, from OUTSIDE the object itself?

I am using Reflections to adjust various values in objects, and I have an object who's parent I need to adjust.

For example:

class Ford extends Car
{
private $model;
}

class Car
{
private $color;
}


I can easily use Reflection to change the model, but how can I separate the parent from the child, so that I can use Reflection on the parent?

Some psuedo code for what I'm hoping is possible:

$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);
}
}


Gist of the question:

In this case, how can I change the $color from outside the object altogether?

Is there something like Ford::parent() or get_parent_object($ford) available?

Note

The objects used above are not the exact scenario, but just used to illustrate the concept. In the real world case, I have a parent/child relationship, and I need to be able to access/change values in each from the outside.

ANSWER

Please check my answer below...I figured it out.

Answer

After extensive review, I have found that I can't access the parent of an object AS AN OBJECT outside of the object itself.

However, using Reflections, I was able to solve the example posted above:

    <?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'

See it in action here: http://codepad.viper-7.com/R45LN0

Comments