Analysis on counter reference of PHP garbage collection mechanism

Source: Internet
Author: User

If you have installed xdebug, you can use xdebug_debug_zval () to display "zval" information. As follows:

Copy codeThe Code is as follows: <? Php
$ Str = "jb51.net ";
Xdebug_debug_zval ('str ');

Result:

Str:
(Refcount = 1, is_ref = 0 ),
String 'jb51. net' (length = 10)

The variable container is destroyed only when "refcount" is changed to 0. when you unset () a variable, the refcount in the desired "zval" will be reduced by 1. Let's talk about the unset reference problem encountered a few days ago:

Copy codeThe Code is as follows: <? Php
$ A = "aaa ";
$ B = & $;
Unset ($ );
// Echo $ B; // aaa will still be output here. Print it with xdebug_debug_zval and you will know why.
Xdebug_debug_zval ("B ");

Result:

B:
(Refcount = 1, is_ref = 0), string 'aaa' (length = 3)
Continue to talk about the reference counter problem. The matching types of array and object are different:

Copy codeThe Code is as follows: <? Php
$ Arr = array ('A' => 'aaa', 'B' => "bbb ");
Xdebug_debug_zval ('arr ');
$ Arr ['aaa'] = $ arr ['a'];
Xdebug_debug_zval ('arr ');
?>

Result:

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)

We can see that the original array elements and newly added array elements are associated with the zval variable container of the same "refcount" 2. Here I am only playing a role in attracting others.

For details about the PHP reference counter can refer to the Manual: http://php.net/manual/zh/features.gc.refcounting-basics.php

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.