We find many developers and individual around the world getting confused over the issue of “Difference between deep copy and shallow copy in PHP.” While this may be an easy nut to crack for the experts, but the new techies often find it difficult to differentiate these two. So, here we are explaining “Deep Copy and Shallow Copy in PHP.”

Before we start discussing the differences between the two, let’s have a look at the diagram to understand if better.

 

Shallow Copy in PHP 

 

Shallow Copy in PHP

This is a bit-wise copy of an object. In Shallow Copy, a new object is created. The new object is an exact copy of the values in the original object. In case if any if any of the fields of the object of the object are references to other objects, only reference addresses get copied.

Example of Shallow Copy


 Deep Copy and Shallow Copy in PHP

 

Output

 

Deep Copy in PHP

 


Deep Copy in PHP

This is a process where the data is actually completely copied. A great advantage of deep copy is that the A & B do not depend on each other but this process is relatively slower and more expensive.

We know that the B points to object A’s memory location in shallow copy. However, in the deep copy, all things in object A’s memory location get copied to object B’s location.

Example

 shallow copy

 

Output

 newly created object

 

You can see clearly that the ID and the Size is different, but the color is same in both results.

When an object is cloned, PHP performs a shallow copy of properties of all subjects. And the properties that are references to other variables will remain references with no changes. After the cloning process, if a __clone() method is defined, then the __clone() method of newly created object will be called. This allows any necessary properties that need to be changed.