0

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?

1
  • 2
    It doesn't say it's a copy. It says something entirely different. Commented Jul 23, 2014 at 14:04

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

To clarify, the documentation specifically says that the copy in PHP 5 is a copy of the identifier, not a copy of the object itself. What John is describing is correct, and agrees with the documentation.
In Linux language, $b is a symlink for $a. In Windows language, $b is a shortcut for $a. Don't kill me for the analogy. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.