Home > Article > Backend Development > Explanation of passing by value and reference in php
This article mainly shares with you the explanation of value transfer and reference in PHP. It is mainly shared with you in the form of text. I hope it can help everyone.
Introduction:
Each php variable exists in a variable container called
"zval"
. Azval
variable container, in addition to containing the type and value of the variable, also includestwo bytes
of additional information. The first one is"is_ref"
, which is abool value
, used to identify whether this variable belongs to thereference set
(referenceset). Through this byte, the PHP engine can distinguish ordinary variables from reference variables. Since PHP allows users to use custom references by using &, there is also aninternal reference counting mechanism
in the zval variable container, to Optimize memory usage. The second byte is"refcount"
, which is used to indicate the number of variables (also called symbols) thatpoints to the
zval variable container. When the value of"refcount"
is1
, the value of "is_ref" is alwaysFALSE
.
Example:
<?php$a = 10; //将常量值赋给变量,会为a分配内存空间$b = $a; //变量赋值给变量,给b分配了内存空间,并将a变量的类型和值复制一份存储到b的存储空间 $c = &$a; //引用是不会为c分配空间的,c和a是共用一份内存空间数据。
When assigning a variable to a new variable in PHP, memory space will not be allocated immediately for the new variable, but a reference to the memory space will be added. When any changes are made to the original variable or the new variable, a memory space will be allocated for the new variable.
Related recommendations:
What is the difference between ordinary value-passing and reference-passing in PHP functions
The above is the detailed content of Explanation of passing by value and reference in php. For more information, please follow other related articles on the PHP Chinese website!