Table of Contents
1. Why the initial value of the reference counter of some variables is 0
二. 为什么在对整形、浮点型和静态字符串型变量进行引用赋值时,计数器的值会直接变为2
现象
原因
三. 为什么初始数组的引用计数器的值为 2
总结
Home Backend Development PHP7 Detailed explanation of the zval structure and reference counting mechanism in PHP7

Detailed explanation of the zval structure and reference counting mechanism in PHP7

Mar 18, 2021 pm 06:16 PM
php7

Detailed explanation of the zval structure and reference counting mechanism in PHP7

Recommended study: "PHP Video Tutorial"

Recently when I was checking the information on PHP7 garbage collection, some code examples on the Internet were found locally. Different results occurred when running in different environments, which made me very confused. If you think about it carefully, it is not difficult to find the problem: most of these articles are from the PHP5. #Mainly focus on explaining the reference counting mechanism in the new zval container. If there are any fallacies, please feel free to give me some advice.

The new zval structure in PHP7

Let’s not talk secretly, let’s look at the code first!

struct _zval_struct {
    union {
        zend_long         lval;             /* long value */
        double            dval;             /* double value */
        zend_refcounted  *counted;
        zend_string      *str;
        zend_array       *arr;
        zend_object      *obj;
        zend_resource    *res;
        zend_reference   *ref;
        zend_ast_ref     *ast;
        zval             *zv;
        void             *ptr;
        zend_class_entry *ce;
        zend_function    *func;
        struct {
            uint32_t w1;
            uint32_t w2;
        } ww;
    } value;
    union {
        struct {
            ZEND_ENDIAN_LOHI_4(
                zend_uchar    type,         /* active type */
                zend_uchar    type_flags,
                zend_uchar    const_flags,
                zend_uchar    reserved)     /* call info for EX(This) */
        } v;
        uint32_t type_info;
    } u1;
    union {
        uint32_t     var_flags;
        uint32_t     next;                 /* hash collision chain */
        uint32_t     cache_slot;           /* literal cache slot */
        uint32_t     lineno;               /* line number (for ast nodes) */
        uint32_t     num_args;             /* arguments number for EX(This) */
        uint32_t     fe_pos;               /* foreach position */
        uint32_t     fe_iter_idx;          /* foreach iterator index */
    } u2;
};
复制代码
Copy after login
For a detailed description of the structure, you can refer to Brother Niao’s article at the end of the article. It is very detailed. I will not show off to others. Here I will only put forward a few key points:

  • Variables in PHP7 are divided into two parts:

    variable name and variable value, which respectively correspond to zval_struct and the ## declared in it. zend_long and double

    in #value
  • ##zval_struct.value are all simple data Type can directly store specific values, while other complex data types store a pointer to other data structures

    In PHP7, the reference counter is stored in
  • value
  • instead of

    zval_struct

  • NULL
  • ,

    Boolean type all belong to There is no data type with value (the Boolean type is marked by two constants IS_FALSE and IS_TRUE), and naturally there is no reference count

  • Reference
  • (REFERENCE) has become a data structure instead of just a mark bit. Its structure is as follows:

    struct _zend_reference {
        zend_refcounted_h gc;
        zval              val;
    }
    Copy after login

    zend_reference
  • As a

    value type contained in zval_struct, it also has its own val value, which points to a zval_struct.value. They all have their own reference counter.

    The reference counter is used to record how many
  • zval
currently point to the same
zend_value. For the sixth point, please see the following code:
$a = 'foo';
$b = &$a;
$c = $a;
Copy after login
The data structure at this time is like this:

$a and $b each have a

zval_struct

container, and the

value in it all point to the same zend_reference structure, zend_reference has an embedded val structure, pointing to the same zend_string, The content of the string is stored in it. And $c also has a zval_struct

, and its value can directly point to the

zend_string mentioned above during initialization, so that it will not Generate a copy. Let’s talk about the various phenomena that will occur in this new zval

structure, and the reasons behind these phenomena.

Question

1. Why the initial value of the reference counter of some variables is 0

Phenomena
$var_int = 233;
$var_float = 233.3;
$var_str = '233';

xdebug_debug_zval('var_int');
xdebug_debug_zval('var_float');
xdebug_debug_zval('var_str');

/** 输出 **
var_int:
(refcount=0, is_ref=0)int 233

var_float:
(refcount=0, is_ref=0)float 233.3

var_str:
(refcount=0, is_ref=0)string '233' (length=3)
**********/
Copy after login

Cause

In PHP7, when assigning a value to a variable, it includes two parts of the operation:

1. Apply for a

zval_struct

structure

for the symbolic quantity (that is, the variable name) 2. Store the value of the variable in zval_struct.value

. For the value that

zval can save in the value field, it will not be used in the corresponding field. They perform reference counting, but assign values ​​ directly when copying. These types are: IS_LONG

    IS_DOUBLE
  • That is our
  • integer
and

floating point type in PHP. So why is the refcount of var_str also 0? This involves two types of strings in PHP:

1,
interned string

Internal strings (function names, class names, variable names, static strings):

 $str = '233';    // 静态字符串
Copy after login
2. Ordinary string:
 $str = '233' . time();
Copy after login

For

internal string

, the content of the string is the only constant, which is equivalent to the definition in C language The strings in the static variable area,

their life cycle exists during the entire request period. After the request is completed, they will be destroyed and released . Naturally, there is no need to use reference counting for memory management.

二. 为什么在对整形、浮点型和静态字符串型变量进行引用赋值时,计数器的值会直接变为2

现象

$var_int_1 = 233;
$var_int_2 = &var_int;
xdebug_debug_zval('var_int_1');

/** 输出 **
var_int:
(refcount=2, is_ref=1)int 233
**********/
Copy after login

原因

回忆一下我们开头讲的 zval_structvalue 的数据结构,当为一个变量赋整形浮点型静态字符串类型的值时,value 的数据类型为 zend_longdoublezend_string,这时值是可以直接储存在 value 中的。而按值拷贝时,会开辟一个新的 zval_struct 以同样的方式将值储存到相同数据类型的 value 中,所以 refcount 的值一直都会为 0。

但是当使用 & 操作符进行引用拷贝时,情况就不一样了:

  • PHP 为 & 操作符操作的变量申请一个 zend_reference 结构

  • zend_reference.value 指向原来的 zval_struct.value

  • zval_struct.value 的数据类型会被修改为 zend_refrence

  • zval_struct.value 指向刚刚申请并初始化后的 zend_reference

  • 为新变量申请 zval_struct 结构,将他的 value 指向刚刚创建的 zend_reference

此时:$var\_int\_1 和 $var_int_2 都拥有一个 zval_struct 结构体,并且他们的 zval_struct.value 都指向了同一个 zend_reference 结构,所以该结构的引用计数器的值为 2。

题外话:zend_reference 又指向了一个整形或浮点型的 value,如果指向的 value 类型是 zend_string,那么该 value 引用计数器的值为 1。而 xdebug 出来的 refcount 显示的是 zend_reference 的计数器值(即 2)

三. 为什么初始数组的引用计数器的值为 2

现象

$var_empty_arr = [1, 2, '3'];
xdebug_debug_zval('var_empty_arr');

/** 输出 **
var_arr:
(refcount=2, is_ref=0)
array (size=3)
  0 => (refcount=0, is_ref=0)int 1
  1 => (refcount=0, is_ref=0)int 2
  2 => (refcount=1, is_ref=0)string '3' (length=1)
**********/
Copy after login

原因

这牵扯到 PHP7 中的另一个概念,叫做 immutable array(不可变数组)。

For arrays the not-refcounted variant is called an "immutable array". If you use opcache, then constant array literals in your code will be converted into immutable arrays. Once again, these live in shared memory and as such must not use refcounting. Immutable arrays have a dummy refcount of 2, as it allows us to optimize certain separation paths.

不可变数组opcache 扩展优化出的一种数组类型,简单的说,所有多次编译结果恒定不变的数组,都会被优化为不可变数组,下面是一个反例:

$array = [1, 2, time()];
Copy after login

PHP 在编译阶段无法得知 time() 函数的返回值,所以此处的 $array 是可变数组

不可变数组和我们上面讲到的内部字符串一样,都是不使用引用计数的,但是不同点是,内部字符串的计数值恒为 0,而不可变数组会使用一个伪计数值 2。

总结

  • 简单数据类型

    • 整形(不使用引用计数)
    • 浮点型(不使用引用计数)
    • 布尔型(不使用引用计数)
    • NULL(不使用引用计数)
  • 复杂数据类型

    • 字符串

      • 普通字符串(使用引用计数,初始值为 1)
      • 内部字符串(不使用引用计数,引用计数值恒为 0)
    • 数组

      • 普通数组(使用引用计数,初始值为 1)
      • 不可变数组(不使用引用计数,使用伪计数值 2)
    • 对象(使用引用计数,初始值为 1)

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Detailed explanation of the zval structure and reference counting mechanism in PHP7. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? Apr 02, 2024 pm 07:39 PM

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

How to solve the problem when php7 detects that the tcp port is not working How to solve the problem when php7 detects that the tcp port is not working Mar 22, 2023 am 09:30 AM

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

How to install mongo extension in php7.0 How to install mongo extension in php7.0 Nov 21, 2022 am 10:25 AM

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

PHP Server Environment FAQ Guide: Quickly Solve Common Problems PHP Server Environment FAQ Guide: Quickly Solve Common Problems Apr 09, 2024 pm 01:33 PM

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

How to install and deploy php7.0 How to install and deploy php7.0 Nov 30, 2022 am 09:56 AM

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Which one is better, php8 or php7? Which one is better, php8 or php7? Nov 16, 2023 pm 03:09 PM

Compared with PHP7, PHP8 has some advantages and improvements in terms of performance, new features and syntax improvements, type system, error handling and extensions. However, choosing which version to use depends on your specific needs and project circumstances. Detailed introduction: 1. Performance improvement, PHP8 introduces the Just-in-Time (JIT) compiler, which can improve the execution speed of the code; 2. New features and syntax improvements, PHP8 supports the declaration of named parameters and optional parameters, making functions Calling is more flexible; anonymous classes, type declarations of properties, etc. are introduced.

Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Why does an error occur when installing an extension using PECL in a Docker environment? How to solve it? Apr 01, 2025 pm 03:06 PM

Causes and solutions for errors when using PECL to install extensions in Docker environment When using Docker environment, we often encounter some headaches...

See all articles