Analysis: PHP garbage collection mechanism

Source: Internet
Author: User
Analysis: PHP garbage collection mechanism

  1. $ A = array (1, 4, 5 );
  2. $ B = $ a; // The array is not copied.
  3. $ A [1] = 10; // The array is copied and the value is modified.
  4. Print_r ($ );
  5. Print_r ($ B );
  6. ?>

After running, the values of $ a and $ B are different. $ A is, 5 $ B is, 5, which is a bit similar to the value assignment of the C # value type. To make $ a and $ B always be the same reference, write the code as follows:

  1. $ B = & $;

A term used in PHP to match the Copy-on-write technology is referred to as reference count ). In PHP, each variable is composed of two parts: a variable name and a variable value. they are stored in a structure called a symbol table, which is an array, it maps the location of the variable name and value in the memory. Each value in the symbol table has a so-called reference count, which records how many methods can be used to obtain this value, that is, how many variable names point to this value.

In the above code, after $ a is initialized, after $ B = $ a, this array has a reference count 2 (if you view the reference count through the C API method, this value is actually 3, but from the user's point of view, it can be better understood as 2 ). The value in the memory can be obtained in two ways, through $ a and $ B. then, when the value of $ a [1] is changed, php creates a new memory space for $ a, that is, two arrays. The reference count of both arrays is 1.

When a variable out of the scope, such as a local variable in the function, the variable becomes invalid after the function is run, the reference count of the value pointed to by this variable is reduced by 1. Similarly, if a variable points to a new memory address, the reference count on the value of this old address will be reduced by 1.

When the reference count of a memory space is 0, it will be released by 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.