Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper OO way to convert an object to one of its subclasses (covariant return type)?

Tags:

oop

php

covariant

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 ?
  }
}
like image 742
aw crud Avatar asked Aug 19 '11 15:08

aw crud


1 Answers

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.

like image 105
hakre Avatar answered Sep 20 '22 07:09

hakre