Is object assignment a reference in PHP?
In previous articles, we talked about the problem of variable assignment, and one of the problems is that when an object performs a variable assignment, it simply does a reference assignment. So what’s the real story?
The previous variable assignment article
PHP variable assignment
Object reference test
After further studying the PHP manual, I found that the object really is not a direct reference copy. Use the following manual example to analyze:
1class SimpleClass
2{}
3
4$instance= new SimpleClass(); 5 and 6$assigned = $instance;
7$reference = &$instance; 8 and 9$instance->var = '$assigned will have this value'; 10 of 11$instance = null; // $instance and $reference become null
12
13var_dump($instance);
14var_dump($reference);
15var_dump($assigned);
Copy the code
-
$instance is the instantiated SimpleClass object
-
$assigned Specifies the value
-
$reference Specifies the reference value
-
First, we define a variable var for the $instance object
-
Then assign $instance to null
-
For references, the $reference variable is also null
-
But $assigned does not become null. It is still an instance of SimpleClass, and, for emphasis: it has a var attribute
Isn’t it amazing that normal assignment is a copy, and the two variables don’t affect each other? While reference assignment copies Pointers (the same memory address), modifying any variable changes other variables as well. But the ordinary assignment of an object does not seem to belong to any of them.
$reference is well understood, and is itself assigned with the & symbol, indicating that the variable is a reference assignment. It becomes a shortcut to $instance and changes with everything $instance changes. This is at the variable level.
$assigned is a normal assignment literally. However, an object is a special form, and the value assigned by a normal assignment is actually a handle to the object. There’s a Note in the PHP manual that describes it this way:
Note: www.php.net/manual/zh/l…
conclusion
Through the analysis of this paper, we can see that variable assignment is simply an operation at the variable level. It’s always just a value. When a normal assignment is made, this value is a primitive type. When a reference is assigned, the saved primitive type is a pointer. However, it does not convert a normal assignment to a reference assignment just because it is holding an object; real reference assignments must be preceded by an ampersand.
This content is a bit convoluted, but such content can better reflect their core capabilities. Read a hundred times its meaning is self-evident, for a lot of knowledge in the manual I also go back and forth to learn to understand. The above Note author wrote very well, English friends can directly go to see the original English.
Test code: github.com/zhangyue050…
Reference documents: www.php.net/manual/zh/l…