Last Updated: February 25, 2016
·
1.148K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside