3.8. Cloning Objects

When creating an object (using the new keyword), the returned value is a handle to an object or, in other words, the id number of the object. This is unlike PHP 4, where the value was the object itself. This doesn't mean that the syntax for calling methods or accessing properties has changed, but the copying semantics of objects have changed.

Consider the following code:

class MyClass {
    public $var = 1;
}

$obj1 = new MyClass();
$obj2 = $obj1;
$obj2->var = 2;
print $obj1->var;

In PHP 4, this code would have printed 1, because $obj2 is assigned the object value of $obj1, therefore creating a copy, leaving $obj1 unchanged. However, in PHP 5, because $obj1 is an object handle (its id number), what is copied to $obj2 is the ...

Get PHP 5 Power Programming 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.