Search code examples
phpooptype-conversiondowncast

Cast the current object ($this) to a descendent class


I have a class where it may be necessary to change the object to a descendent class further down the line. Is this possible? I know that one option is to return a copy of it but using the child class instead, but it'd be nice to actually modify the current object... so:

class myClass {
  protected $var;

  function myMethod()
  {
    // function which changes the class of this object
    recast(myChildClass); 
  }
}

class myChildClass extends myClass {
}

$obj = new myClass();
$obj->myMethod();
get_class_name($obj); // => myChildClass

Solution

  • You can, as described in other answers, do it with nasty black magic PECL extensions.

    Though, you seriously don't want it. Any problem you want to solve in OOP there's an OOP-compliant way to do it.

    Runtime type hierarchy modifications are not OOP-compliant (in fact, this is consciously avoided). There are design patterns that should fit what you want.

    Please, tell us why do you want that, I'm sure there must be better ways to do it ;)