Search code examples
phpoopinheritanceclone

Can I create a child class out of a parent class?


Lets say I have a class that is responsible for composing another class:

class ClassBuilder
{
    protected $baseClass;

    public function __construct()
    {
        $this->baseClass = new BaseClass();
    }

    public function set()
    {
        $this->baseClass->foo = 'bar';
    }

    // other methods to further modify BaseClass
}

class BaseClass
{
    public $foo;
}
class ChildClass extends BaseClass {}

I want to create a method in the ClassBuilder that would allow me to update its baseClass property to an instance of ChildClass with the same property values as the current BaseClass object. How can I do that?

public function update()
{
    // $this->baseClass = new ChildClass() with the current property values in BaseClass
}

Solution

  • I'm not sure that your overall approach is correct, but about the only way is to loop and set:

    public function update()
    {
        $new = new ChildClass();
    
        foreach($this->baseClass as $name => $value) {
            $new->$name = $value;
        }   
        $this->baseClass =  $new;
        //or
        $this->baseClass = clone $new;
    }