how to clone object to child class in php

2019-03-25 04:45发布

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条回答
我想做一个坏孩纸
2楼-- · 2019-03-25 04:59

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 );
查看更多
登录 后发表回答