Reputation: 1299
Does PHP duplicate an object when =
is used or does it just create a new pointer that points to an already existing object?
Are both of these the same?
$obj1 = new object();
$obj2 = $obj1;
$obj1 = new object();
$obj2 = clone $obj1;
Upvotes: 1
Views: 49
Reputation: 237827
In PHP 4 (i.e. ancient history) objects were indeed copied on assignment. This was not helpful behaviour.
Since PHP 5, objects are now assigned by reference, unless they are cloned.
You can easily test this:
$obj1 = new object();
$obj2 = $obj1;
var_dump($obj1 === $obj2); // bool(true)
$obj1 = new object();
$obj2 = clone $obj1;
var_dump($obj1 === $obj2); // bool(false)
Upvotes: 5