home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Book HomePHP CookbookSearch this book

7.5. Cloning Objects

7.5.2. Solution

Use = to assign the object to a new variable:

$rabbit = new rabbit;
$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.