mercredi 7 juin 2017

Access the parent object of an object in PHP

This is my test code:

class Base
{
    public $property;

    public function method() {
        return 456;
    }

    public function setProperty($value) {
        $this->property = $value;
    }
}

class Derived extends Base
{
    public function method() {
        return 'def';
    }
}

$derived = new Derived;
$derived->setProperty(123);

$base = getParentInstance($derived);

echo $base->property; // Should print 123
echo $base->method(); // Should print 456

Looking around I found a lot of stuff related but nothing direct to the point. I just need to cast an instance to an ancestor class. Is this even possible on PHP?

Up to now I came out with this wrong code that (I think) just instantiate a new Base class:

function getParentInstance($object)
{
    $reflection = new ReflectionObject($object);
    $parent_class = $reflection->getParentClass();
    return $parent_class->newInstanceWithoutConstructor();
}

Another complication is I can only modify Derived... Base is provided by an external framework.





Aucun commentaire:

Enregistrer un commentaire