Is it possible in PHP that a object transforms itself into one of his children class.
example
class Children1 extends Parent {
// the children
}
class Parent {
public function loadChildConfiguration($type){
select($type){
case 1: self::MAGICALLY_TRANSFORM_INTO(Children1); break;
case 2: self::MAGICALLY_TRANSFORM_INTO(Children2); break;
// etc...
}
}
}
$foo = new Parent(); // foo is a Parent
$foo->loadChildConfiguration(1); // foo is now a Children1
For now the only idea I had was to create a static class in the parent as new constructor
class Parent {
public static constructByType($type){
select($type){
case 1: $class = Children1; break;
case 2: $class = Children2; break;
// etc...
}
return new $class;
}
}
$bar = Parent::constructByType(1); // bar is a Children1
This should work as far as I do not need to get the children class after the parent creation.
Is there a way to change an object to its child after it has been created? Maybe there is another "cleaner" way to load new methods and parameter to an existing object?