Home » Php » PHP Deep Object Copy/Clone

PHP Deep Object Copy/Clone

Posted by: admin July 12, 2020 Leave a comment


What is the best accepted way in PHP to perform a deep object copy/clone?

I have found some examples using serialize which i think suffers from some issues.

How to&Answers:

If you have full access to your classes, you can implement __clone() in all of them and then use the clone keyword. Otherwise the clone keyword will just create a shallow copy of the topmost object, while potential references within this object will continue to point at their original targets. The __clone() method also gives you more control, but may create endless loops with cyclic references, if you don’t deal with them explicitly.

The serialization technique generally works, does not die on cyclic references, but is more expensive in terms of memory and CPU.