Disclaimer: The intent of this blog post is not for you to stop using the clone keyword but to raise
awareness of its behavior since IMO in the documentation is not that clear.
As you know, PHP has a well-known clonekeyword that shallow copy all of the object’s properties.
So under the hood what it does is to create a new Object with the exact same values of that object properties –
unless you change its behavior by implementing the __clone() function in your class.
This behavior seems what we expected. However, it might give “weird” results if the object that you are cloning contains properties that are objects. Let’s see:
So these are two simple classes, one for my Car another for its Model. So now let’s see what happens when we create a new Car, clone it and change a model name of one of them.
Would you expect this result? Probably not. So what’s happening here? PHP does not regenerate the memory address of
objects that are properties in the object you are cloning nor traverses those properties to regenerate them.
So how can we solve this? Fortunately, there is a Library for it!
The DeepCopy lib is what we need. What DeepCopy does is
recursively traverses all the object’s properties and clones them ensuring that every object inside the object you
are cloning has a new instance of it hence it will have a new object Id. Let’s see a visual representation at how clone and DeepCopy works.
Let’s see how we can fix the code.
And it’s solved! I hope this helps you understand a bit better the clone keyword. Use it wisely.