Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Daniel Gomes:
Don’t clone your php objects, DeepCopy them
Sep 12, 2018 @ 14:46:10

On his site, Daniel Gomes has written up an article that makes a suggestion about working with objects in PHP. In it, he suggests performing a deep copy of them rather than just cloning them into a new variable.

As you know, PHP has a well-known clone keyword 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.

He gives an example of this "weird" result when cloning an object that has a model property containing an instance of a CarModel class. He shows the hash IDs for the objects (different), the model properties (the same) and how changing one changes the other. This could lead to some unintended consequences so he suggests a deep copy instead using a handy library. He finishes the post with example code using this library and the resulting hashes/value differences.

tagged: clone object deepcopy tutorial difference hash

Link: https://dcsg.me/articles/dont-clone-your-php-objects-deepcopy-them/


Trending Topics: