O'Reilly logo

PHP 5 Power Programming by Derick Rethans, Stig Sæther Bakken, Andi Gutmans

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required