Home >Backend Development >PHP Tutorial >In-depth analysis of PHP's reference counting mechanism_PHP tutorial
After PHP variables are declared and assigned, the variable name is stored in the symbol table, and the value and class information are stored in zval. Zval contains four variables, is_ref, refcount, value, type, zvalThe source code is as follows
Here is an analysis of when zval will be copied or new memory space opened up
1. When is_ref=0, and refcount>1, if it changes The value of a variable pointing to the zval will generate a new zval, the refcount of the original zval--, for example: $a=1;$b=$a;$b=2;, the zval will be copied, that is to say, the original zval ab points to the same zval, and later b will use the newly opened zval
2. When is_ref=0, and refcount>1, if zval is assigned to a reference variable, then it is used to assign the value and the variable sum The assigned variable will use the same original zval, and other variables pointing to the original zval will point to a newly copied zval, and the refcount will be recalculated, for example: $a=1;$b=$a;$c= $a;$d=&$a;, at this time ad uses the original zval, and bc uses the newly copied zval
3. When is_ref=1 and refcount>1, if zval is copied to someone A non-reference variable, the non-reference variable will use a newly copied zval, and the refcount of the original zval remains unchanged. For example: $a=1;$b=&$a;$c=$a, then ab uses the original zval, And c uses the newly copied zval
type to represent the value type of the zval. The macro definition is as follows: