浅析PHP原理之变量分离/引用(Variables Separation)
首先我们回顾一下zval的结构:
复制代码 代码如下:
struct _zval_struct {
/* Variable information */
zvalue_value value; /* value */
zend_uint refcount;
zend_uchar type; /* active type */
zend_uchar is_ref;
};
其中的refcount和is_ref字段我们一直都没有介绍过,我们知道PHP是一个长时间运行的服务器端的脚本解释器。那么对于它来说,效率和资源占用率是一个很重要的衡量标准,也就是说,PHP必须尽量介绍内存占用率,考虑下面这段代码:
复制代码 代码如下:
$var = "laruence";
$var_dup = $var;
unset($var);
?>
第一行代码创建了一个字符串变量,申请了一个大小为9字节的内存,保存了字符串”laruence”和一个NULL(/0)的结尾。
第二行定义了一个新的字符串变量,并将变量var的值”复制”给这个新的变量。
第三行unset了变量var
这样的代码在我们平时的脚本中是很常见的,如果PHP对于每一个变量赋值都重新分配内存,copy数据的话,那么上面的这段代码公要申请18个字节的内存空间,而我们也很容易的看出来,上面的代码其实根本没有必要申请俩份空间,呵呵,PHP的开发者也看出来了:
我们之前讲过,PHP中的变量是用一个存储在symbol_table中的符号名,对应一个zval来实现的,比如对于上面的第一行代码,会在symbol_table中存储一个值”var”, 对应的有一个指针指向一个zval结构,变量值”laruence”保存在这个zval中,所以不难想象,对于上面的代码来说,我们完全可以让”var”和”var_dup”对应的指针都指向同一个zval就可以了。
PHP也是这样做的,这个时候就需要介绍我们之前一直没有介绍过的zval结构中的refcount字段了。
refcount,顾名思义,记录了当前的zval被引用的计数。
比如对于代码:
复制代码 代码如下:
$var = 1;
$var_dup = $var;
?>
第一行,创建了一个整形变量,变量值是1。 此时保存整形1的这个zval的refcount为1。
第二行,创建了一个新的整形变量,变量也指向刚才创建的zval,并将这个zval的refcount加1,此时这个zval的refcount为2。
PHP提供了一个函数可以帮助我们了解这个过程debug_zval_dump:
复制代码 代码如下:
$var = 1;
debug_zval_dump($var);
$var_dup = $var;
debug_zval_dump($var);
?>
输出:
long(1) refcount(2)
long(1) refcount(3
如果你奇怪 ,var的refcount应该是1啊?
我们知道,对于简单变量,PHP是以传值的形式穿参数的。也就是说,当执行debug_zval_dump($var)的时候,$var会以传值的方式传递给debug_zval_dump,也就是会导致var的refcount加1,所以我们只要能看到,当变量赋值给一个变量以后,能导致zval的refcount加1这个事实即可。
现在我们回头看文章开头的代码, 当执行了最后一行unset($var)以后,会发生什么呢? 对,既是refcount减1,上代码:
复制代码 代码如下:
$var = "laruence";
$var_dup = $var;
unset($var);
debug_zval_dump($var_dup);
?>
输出:
string(8) "laruence" refcount(2
但是,对于下面的代码呢?
复制代码 代码如下:
$var = "laruence";
$var_dup = $var;
$var = 1;
?>
很明显在这段代码执行以后,$var_dup的值应该还是”laruence”, 那么这又是怎么实现的呢?
这就是PHP的copy on write机制:
PHP在修改一个变量以前,会首先查看这个变量的refcount,如果refcount大于1,PHP就会执行一个分离的例程, 对于上面的代码,当执行到第三行的时候,PHP发现$var指向的zval的refcount大于1,那么PHP就会复制一个新的zval出来,将原zval的refcount减1,并修改symbol_table,使得$var和$var_dup分离(Separation)。这个机制就是所谓的copy on write(写时复制)。
上代码测试:
复制代码 代码如下:
$var = "laruence";
$var_dup = $var;
$var = 1;
debug_zval_dump($var);
debug_zval_dump($var_dup);
?>
输出:
long(1) refcount(2)
string(8) "laruence" refcount(2
现在我们知道,当使用变量复制的时候 ,PHP内部并不是真正的复制,而是采用指向相同的结构来尽量节约开销。那么,对于PHP中的引用,那又是如何实现呢?
复制代码 代码如下:
$var = "laruence";
$var_ref = &$var;
$var_ref = 1;
?>
这段代码结束以后,$var也会被间接的修改为1,这个过程称作(change on write:写时改变)。那么ZE是怎么知道,这次的复制是不需要Separation的呢?
这个时候就要用到zval中的is_ref字段了:
对于上面的代码,当第二行执行以后,$var所代表的zval的refcount变为2,并且同时置is_ref为1。
到第三行的时候,PHP先检查var_ref代表的zval的is_ref字段,如果为1,则不分离,大体逻辑示意如下:
复制代码 代码如下:
if((*val)->is_ref || (*val)->refcount //不执行Separation
... ;//process
}
但是,问题又来了,对于如下的代码,又会怎样呢?
复制代码 代码如下:
$var = "laruence";
$var_dup = $var;
$var_ref = &$var;
?>
对于上面的代码,存在一对copy on write的变量$var和$var_dup, 又有一对change on write机制的变量对$var和$var_ref,这个情况又是如何运作的呢?
当第二行执行的时候,和前面讲过的一样,$var_dup 和 $var 指向相同的zval, refcount为2.
当执行第三行的时候,PHP发现要操作的zval的refcount大于1,则,PHP会执行Separation, 将$var_dup分离出去,并将$var和$var_ref做change on write关联。也就是,refcount=2, is_ref=1;
基于这样的分析,我们就可以让debug_zval_dump出refcount为1的结果来:
复制代码 代码如下:
$var = "laruence";
$var_dup = &$var;
debug_zval_dump($var);
?>
输出:
string(8) "laruence" refcount(1
详细原因,读者你只要稍加分析就能得出,我就不越俎代庖了。;)
这次我们介绍了PHP的变量分离机制,下次我会继续介绍如果在扩展中接收和传出PHP脚本中的参数。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7
