Today one of my team member had asked that, “Why we clone the Objects in PHP?”. I was surprised with the question for few seconds. Then I have made a quick search and found the answer for the same.
Full detailed question is just like “Why we use object cloning even if we can create copy of an object using = operator.”
So I thought it would be good to share this answer, so it will make clear to all who has the same question in their mind. In one of my earlier post I have explined that, creating a copy with clone keyword will make and object copy of the the class. Just like creating another set of varibales.
Why we use object cloning even if we can create copy of an object using = operator.
When you create a copy of any object using = operator then it will create a copy but with reference to the main variable. So after copying the object in this way, if you make any changes in variable of one object will affect to variable of both the objects. Have a look at below code block for more detail:
You can see that we have copied the object using = operator, and when you make changes in property of one object then it will reflect to other also.
Note: clone keyword will create a exact copy of an object.
Now let’s see how the clone keyword works. Have a look at the below code block which creates the clone of the object using the clone keyword. After cloning the object of the class if you make changes in property of main class then it will not affect the property of the other class which we have cloned using the clone keyword. Its just like an new varibles rather than assign variables by reference.
So now you have to decide which one to use based on your need either clone keyword or = operator.
Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.
View all posts by: Avinash