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 789;
}
}
$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.
Addendum
Here is the proof what I'm requesting is not absurd. Same code in C++:
class Base
{
public:
int property;
int method() {
return 456;
}
void setProperty(int value) {
this->property = value;
}
};
class Derived: public Base
{
public:
int method() {
return 789;
}
};
#include <iostream>
int main()
{
Derived *derived = new Derived;
derived->setProperty(123);
Base *base = (Base *) derived; // Is **this** possible in PHP?
std::cout << base->property; // It prints 123
std::cout << base->method(); // It prints 456
return 0;
}