In PHP, most variable types, such as strings, integers, floating-point, arrays, and so on, are value types, and classes and objects are reference types, which you need to be aware of when you use them.
See the user in the discussion of PHP & symbol, to thoroughly understand its usage, it is necessary to discuss the two forms of variables.
PHP variables are stored in memory, and variables are not stored directly in the content of the value, but in the address. For example:
It seems to us that the variable $a directly stores the value of 1. The reality is that the PHP interpreter creates a variable $a that stores the value: 1 somewhere in memory and then saves the address of the value to the variable $a.
When you need to take a value, you first find the address in the variable $a, and then find the value of the variable based on the address.
Look down:
Output the 1,php interpreter will do the same code: find the address stored in the $a, find the value of somewhere in memory based on the address, and output it to the screen.
It looks like a simple line of code, but that's the process.
And look down:
Here's the variable $b do an interesting operation the,& symbol takes out the address stored in the $a variable and stores it to the $b variable.
So, if you use the following code:
The result will also be the output 1,php interpreter that first takes out the address stored in the $b and then finds the value based on the address. If we do the following:
$a = 2;
Echo $b; Output 2
You will find that you change the value of the $a, and $b changes accordingly. In fact, in turn, change the value of the $b, $a value will also change with this.
In this step, we can determine that the variable $a and $b store the same address, pointing to the same value.
So, we can draw the conclusion that they represent the same variable.
As a further summary, it can be concluded that if two variables store the same address, they are the same variable.
Having learned something, we began to introduce value types and reference types.
We'll look at the following code:
$a = 1;
$b = $a;
$a = 2;
Echo $b; Output 1
Assigning the value of $a to $b, changing the value of the $a, the value of the $b remains unchanged, which means that $a and $b are two different variables that point to different addresses. This assignment creates a different form of the variable that we call the value type.
Look again:
Class user{public
$name = ' tome ';
}
$a = new User;
$b = $a;
$a->name = ' Jim ';
Echo $b->name; Output Jim
Similarly, the value of $a is assigned to $b, and after the $a is changed, the $b changes, which means that $a and $b are the same variable, pointing to the same address. This assignment does not create a new form of the variable we call the reference type.