Home > Article > Backend Development > Questions about PHP variable separation and reference
Today I read Brother Niao’s article about PHP variable separation and reference. There is a problem that I didn’t understand. I’ll post some screenshots first:
If you follow the above statement, then I will slightly modify the code as follows:
<code><?php $var = "laruence"; $var_dup = &$var; $var_ref = &$var; $var_ref = "OK"; ?> </code>
Then
Second line of code:
$var_dup and $var point to the same zval with refcount of 2.
When executing the third line:
PHP finds that the refcount of the zval to be operated is greater than 1, then PHP will execute Separation, separate $var_dup, and associate $var and $var_ref with change on write. That is, refcount=2, is_ref=1;
When proceeding to the fourth line:
Since $var and the zval pointed to by $var_ref have is_ref=1;, they will not be separated, making the values of $var_ref and $var both "OK".
According to my understanding, at the end of the program, since $var_dup has been separated when executing the third line, its value should remain "laruence" unchanged. However, when I ran the program, I found that it also changed. It became "OK", which makes me very confused. I hope someone who knows the answer can help me. I don’t know if I understood it wrong or if there is another hidden meaning, thank you!
Attached are two small chestnuts for your reference:
<code><?php $var = "laruence"; $var_ref = "OK"; $var_dup = &$var; $var = &$var_ref; echo $var; //OK echo $var_dup; //laruence echo $var_ref; //OK ?> </code>
<code><?php $var = "laruence"; $var_ref = "OK"; $var_dup = &$var; $var_ref = &$var; echo $var; //laruence echo $var_dup; //laruence echo $var_ref; //laruence ?> </code>