Book HomePHP CookbookSearch this book

7.5. Cloning Objects

7.5.1. 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.

7.5.2. Solution

Use = to assign the object to a new variable:

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

7.5.3. 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.

7.5.4. See Also

Recipe 7.6 for more on assigning objects by reference.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.