Last Updated: February 25, 2016
·
834
· agripinoduarte

Cloning PHP Objects

The '=' operator, by default, make a shallow copy of the object (the object copied has the same reference to the original):

$obj1 = new ObjectType();
$obj2 = $obj1; // $obj2 refers the same memory address of $obj1

To perform a deep copy (create a new object of same type with same atributes) we use the 'clone' reserved word:

$obj1 = new ObjectType();
$obj2 = clone $obj1; // $obj2 refers a new memory address that holds a copy of $obj1, atribute by atribute.

Note that if atributes of $obj1 are also references to objects, 'clone' will perform a shallow copy of them, i.e, use the same reference to them.