Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? Thanks

like image 997
MMiroslav Avatar asked Oct 14 '12 12:10

MMiroslav


People also ask

Does PHP support object cloning?

An object copy is created by using the clone keyword (which calls the object's __clone() method if possible). $copy_of_object = clone $object; When an object is cloned, PHP will perform a shallow copy of all of the object's properties. Any properties that are references to other variables will remain references.

What is deep cloning in PHP?

Deep copy creates a copy of an object and recursively creates a copy of the objects referenced by the properties of the object. Since PHP calls the __clone() method automatically after cloning an object, you can clone the objects referenced by the properties of the class.


1 Answers

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 );
like image 98
Oras Avatar answered Sep 21 '22 12:09

Oras