Cloning Objects in PHP

While recently trying to add a new feature to my meta box plugin for WordPress, I decided to just rewrite it so that it can accommodate my goals for the plugin. It’s all very interesting timing since I’m trying to be active in the CEUX and Metamorphosis projects on make.wordpress.org, but that’s a different blog post.

So in rewriting, I’ve converted my giant 1-Class system with a huge array to handle all the fields, into a slightly more structured class based system where I now have objects that I can do more with rather than a bunch of arrays. Also, since I was in the process of renaming the plugin anyway, I thought I would go ahead and do that while I’m changing the plugin structure.

I made an interesting discovery that some might already know but since I spent several hours figuring it out, I felt the need to write a blog post and maybe help someone along the way. In PHP 4, to clone an object (or make a copy), you can simply just assign it to a new variable:

This gives you the ability to make a copy without affecting the original. In PHP 5, however, objects are always passed by reference. ALL OF THEM. This is the key. So that means this same code in PHP 5 won’t make a copy, but actually just duplicate it. In order to make an actual copy that you can modify separately, you need to clone it:

So again, nothing super new here except one thing that took me quite a while to figure out. That is if your object contains other objects, those objects remain a reference rather than getting cloned together. For example:

In this case $new_object is a clone of $object, however $new_object->child’s reference remains. So changing $object->child is the same as changing $new_object->child. If you browse through the comments on php.net’s page of cloning objects, you’ll see a few ways of automating this type of clone, however I wanted a bit more control, so I just wrote a custom “duplicate” method that works like this:

This will override the originals and give you nice clean clones ready for manipulation. Maybe I’m really late in the game on this subject, but I hope this ends up helping someone.

Write a Comment