PHP garbage collection mechanism references counter concept analysis
- 2020-06-19 09:52:14
- OfStack
If you have xdebug installed, you can display the "zval" message with xdebug_debug_zval(). As follows:
<?php
$str = "ofstack.com";
xdebug_debug_zval('str');
Results:
str:
(refcount=1, is_ref=0),
string 'ofstack.com' (length=10)
Only the variable container is destroyed when it becomes zero in "refcount". When you have a variable in unset(), the desired "refcount" is subtracted by 1.
<?php
$a = "aaa";
$b = & $a;
unset($a);
//echo $b; // It's still going to print aaa, with xdebug_debug_zval Print it and you'll see why
xdebug_debug_zval("b");
Results:
b:
(refcount=1, is_ref=0),string 'aaa' (length=3)
Moving on to the reference counter problem, it's not the same for array and object that are type-compliant:
<?php
$arr = array( 'a' => 'aaa', 'b' => "bbb" );
xdebug_debug_zval( 'arr' );
$arr['aaa'] = $arr['a'];
xdebug_debug_zval( 'arr' );
?>
Results:
arr:
(refcount=1, is_ref=0),
array
'a' =
>
(refcount=1, is_ref=0),string 'aaa' (length=3)
'b' =
>
(refcount=1, is_ref=0),string 'bbb' (length=3)
arr:
(refcount=1, is_ref=0),
array
'a' =
>
(refcount=2, is_ref=0),string 'aaa' (length=3)
'b' =
>
(refcount=1, is_ref=0),string 'bbb' (length=3)
'aaa' =
>
(refcount=2, is_ref=0),string 'aaa' (length=3)
You can see that the original array element and the newly added array element are associated with the same zval variable container as the "refcount"2. I'm just starting the ball rolling here.
Specific about PHP counter can consult reference manual: http: / / php net manual/zh/features gc. refcounting - basics. php