What is deep copy and shallow copy? How PHP uses them?

I got this question in an interview. Was aware of this conception and explained properly. But I think this topic is worth to explain, so that’s why this post is-

Shallow copy– In the process of shallow copying A, B will copy all of A’s field values. If the field value is a memory address it copies the memory address, and if the field value is a primitive type it copies the value of the primitive type. In layman’s term, shallow copy duplicates as minimum as possible. But the disadvantage is if you modify the memory address that one of B’s fields point to, you are also modifying what A’s fields point to.

Deep copy– In this process the data is actually copied completely. The advantage is that A and B do not depend on each other but this process is relatively slower and more expensive.

So, In a shallow copy object B points to object A’s memory location. In a deep copy, all things in object A’s memory location get copied to object B’s memory location.

When an object is cloned, PHP performs a shallow copy of all of the object’s properties. Any properties that are references to other variables, will remain references. Once the cloning is complete, if a __clone() method is defined, then the newly created object’s __clone() method will be called, to allow any necessary properties that need to be changed. [Object Cloning]

One of the key-points of PHP 5 OOP that is often mentioned is that “objects are passed by references by default”. This is not completely true.

A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn’t contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object.

[Objects and references]

We know how variable reference works in PHP, let me explain how we can relate it here-

$ php referenceTest.php

Copied by reference
2
2

Copied by Value
1
2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s