I have a subclass that needs to return a subclass of the return type of its parent class. I believe this is called a covariant return type. I am wondering the simplest way to convert from the parent to the child class.
class A {
}
class B extends A {
function bar() {
}
}
class Car {
function foo() {
return new A();
}
}
class BrokenCar extends Car {
function foo() {
$a = parent::foo();
//What is the cleanest way to convert $a to type B ?
}
}
In PHP you can not "convert" objects from type/class A to B with a feature available in the language.
You can do so however by making use of serialization if your objects support it (normally plain old PHP objects do support serialization). In the serailized form you change the class of the object and unserialize it again. A has turned into B then. But that's not really fluent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With