user2882597
user2882597

Reputation: 424

Has PHP always made copies when using object assignment?

For example, I have the following class.

class A {
  public $foo = 1;
}  

$a = new A;
$b = $a; // a copy of the same identifier (NB)

According to the current PHP docs a copy of the identifier is made, has this always been the case? If not, when did it change?

Upvotes: 0

Views: 45

Answers (1)

John Conde
John Conde

Reputation: 219804

This wasn't always the case. In PHP4 an object was copied when assigned to a new variable. When PHP5 was introduced this changed to pass a reference of the object being assigned.

(From the manual)

In PHP 5 there is a new Object Model. PHP's handling of objects has been completely rewritten, allowing for better performance and more features. In previous versions of PHP, objects were handled like primitive types (for instance integers and strings). The drawback of this method was that semantically the whole object was copied when a variable was assigned, or passed as a parameter to a method. In the new approach, objects are referenced by handle, and not by value (one can think of a handle as an object's identifier).

Upvotes: 7

Related Questions