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.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you have full access to your classes, you can implement
__clone()in all of them and then use theclonekeyword. Otherwise theclonekeyword 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.