7.4. Cloning Objects

Problem

You want to make a copy of an existing object. For instance, you have an object containing a message posting and you want to copy it as the basis for a reply message.

Solution

Use = to assign the object to a new variable:

$rabbit = new rabbit;
$rabbit->eat();
$rabbit->hop();
$baby = $rabbit;

Discussion

In PHP, all that’s needed to make a copy of an object is to assign it to a new variable. From then on, each instance of the object has an independent life and modifying one has no effect upon the other:

class person {
    var $name;

    function person ($name) {
        $this->name = $name;
    }
}

$adam = new person('adam');
print $adam->name;    // adam
$dave = $adam;
$dave->name = 'dave';
print $dave->name;    // dave
print $adam->name;    // still adam

Zend Engine 2 allows explicit object cloning via a _ _clone( ) method that is called whenever an object is copied. This provides more finely-grained control over exactly which properties are duplicated.

See Also

Recipe 7.6 for more on assigning objects by reference.

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.