how to clone object to child class in php

2019-03-25 04:57发布

问题:

I have a parent class A, and child class B in PHP. Is there any way to clone instance of class A to instance of B, and to use B class properties later in B instance? Thanks

回答1:

My solution will be based on the solution from this question How do you copy a PHP object into a different object type

class childClass extends parentClass
{
    private $a;
    private $b;

    function loadFromParentObj( $parentObj )
    {
        $objValues = get_object_vars($parentObj); // return array of object values
        foreach($objValues AS $key=>$value)
        {
             $this->$key = $value;
        }
    }
}

$myParent = new parentClass();
$myChild = new childClass();
$myChild->loadFromParentObj( $myParent );