how to clone object to child class in php

后端 未结 1 2056
暖寄归人
暖寄归人 2021-02-07 09:13

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条回答
  • 2021-02-07 09:15

    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 );
    
    0 讨论(0)
提交回复
热议问题