[PHP] Variable value transfer-value transfer and reference transfer

It should be the same as the C language (maybe because they are all based on C), here is written in PHP language.

One, value transfer

Value transfer is the most common transfer. The variables a = 1, $b = $a and so on that you usually see are all value transfers.

The way it is passed is-copy the value saved by the original variable, and save the newly copied value to another variable, that is, the copied variable is not affected in any way. E.g:

$a = 1;
$b = $a;
echo $a,$b;

At this time, the output should all be 1.

But it should be noted that the memory at this time should be like this: Note:
Note: Variables store addresses, that is, both a and b store the addresses where two 1's are located.

In this case, if we change $b, it will not affect a:

$a = 1;
$b = $a;
$b = 2;
echo $a,$b;

The result at this time is 1 and 2, that is, a or a.

Two, pass by reference

Passing by reference is to pass the memory address where the value of the variable is stored to another variable-that is, two variables point to the same memory space (also the same value):

$a = 1;
$b = &$a;
echo $a,$b;

At this time, the result is still all 1, but the situation in the memory is:

Insert picture description here
In this case, if we change $b again, it will directly change the value of a:

$a = 1;
$b = &$a;
$b = 2;
echo $a,$b;

In this case, the result is two 2s.

Guess you like

Origin blog.csdn.net/qq_44899247/article/details/105299121