phpclassinheritance

How to clone object to child class in php


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?


Solution

  • 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 );