I am trying to assign an ancestor(A) to descendant(B) type variable and call descendant method on ancestor in PHP but I can't get it working.
class B extends A{
public function c(){ echo 'B.c'}
}
I have tried:
Rewriting B
constructor
class B extends A{
public function __construct($parent)
{
$this = $parent;
}
...
}
$this
cannot be rewritten, so it's a no-go.
This thing I am forgetting how is it called
function d(B $b){
$b = new A();
b.c();
}
Explicit type casting
function d(){
$b = (B) new A();
b.c();
}
Or
function d(){
$b = settype(new A(),'B');
b.c()
}
This doesn't work either as settype
only allows certain types not other user defined object types.
All the information I've seen suggests that there is no clean way to modify an object's type. (PHP merely fakes certain kinds of casting, e.g. there is an (int)
operator but type int
is unknown by itself.)
The approaches I've found are of two types:
Serialize your object, hack the string to modify its type, deserialize. (See here or here-- equivalent). Or
Instantiate a new object and copy over all its properties. (See here)
I'd go with the second approach since you seem to be dealing with a known object hierarchy:
class B extends A {
public function __construct(A $object) {
foreach($object as $property => $value) {
$this->$property = $value;
}
}
}
If you have some control over the creation of the original object, consider implementing a factory pattern so that you object is created with type B
from the start.