The content of this article is about the analysis of references and garbage collection in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Each PHP variable exists in a variable container called "zval". A zval variable container contains, in addition to the type and value of the variable, two bytes of additional information. The first one is "is_ref", which is a bool value used to identify whether this variable belongs to the reference set. 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 an internal reference counting mechanism in the zval variable container to optimize memory usage. The second extra byte is "refcount", which is used to indicate the number of variables (also called symbols) pointing to this zval variable container. All symbols exist in a symbol table, where each symbol has a scope (scope), the main script (for example: the script requested through the browser) and each function or method also have a scope.
//Objects in php are passed by reference
is_ref = 0, refcount = 0 zval container will be destroyed at the end of script execution
Quote from the official example
<?php $a = array( 'one' ); $a[] =& $a; xdebug_debug_zval( 'a' );
a: (refcount=2, is_ref=1)=array ( 0 => (refcount=1, is_ref=0)='one', 1 => (refcount=2, is_ref=1)=... )
Executing unset$a will release the memory association between the variable and zval, but the closed loop itself still exists
(refcount=1, is_ref=1)=array ( 0 => (refcount=1, is_ref=0)='one', 1 => (refcount=1, is_ref=1)=... )
But no variables can be manipulated to zval at this time. The container time has become memory garbage and cannot be released.
Recycling mechanism: To put it simply, after executing the script, the remaining Existing variables will be used for all refcount of the overall data -1. If it is reduced to 0, it will be judged as garbage and the memory container will be destroyed.
Related recommendations:
PHP garbage collection mechanism—basic knowledge of reference counting
The above is the detailed content of Analysis of references and garbage collection in php. For more information, please follow other related articles on the PHP Chinese website!