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.
Use = to assign the object to a new variable:
$rabbit = new rabbit; $rabbit->eat(); $rabbit->hop(); $baby = $rabbit;
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.
Recipe 7.6 for more on assigning objects by reference.
Copyright © 2003 O'Reilly & Associates. All rights reserved.