Main Content

Copying, duplicating, cloning an object in PHP

Archive - Originally posted on "The Horse's Mouth" - 2012-08-18 21:21:16 - Graham Ellis

If you want to copy an object, how do you do it?

Typically, you can just assign the object to a new variable - in PHP, for example:

  $demo = new thing("Stick of Celery");
  $showme = $demo;


but you need to be careful, because that assigns a second name to the same object. If you then run a method on the object by one name, you'll alter the object as it would be under the second name too. Let me show you:

  $showme->set("and zalt");
  print $demo->get();
  print $showme->get();


and I get

  Stick of Celery and zalt
  Stick of Celery and zalt


In practise, this type of copying is usually what you want to do and in scenarios where you don't need to duplicate the internals of the object, it's also very efficient. However, there are times where you want to duplicate the contents of the object so you end up with two identical objects, and you can do this using the clone function that's provided in PHP. Here's how you call it:

  $yummy = clone ($demo);

and when I then change one of my objects:

  $yummy->set("and vinegar");
  print $demo->get();
  print $yummy->get();


I get:

  Stick of Celery and chips
  Stick of Celery and chips and vinegar


in other words I now have two different objects.

The full source code of this example is [here] on our web site, and the topic is covered in our Obejct Oriented Programming in PHP course.

Beware that in PHP 4 - now an old version of PHP that's becoming quite rare - the assignment of an obeject worked just like a clone. This change (which broke a few programs) makes the current (PHP5) version more efficient and also 'correct' from a computer scientist's viewpoint. It's also the original reason for the version number change from "4" to "5".