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
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.
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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With