search
HomeBackend DevelopmentPHP Tutorial浅析PHP原理之变量分离/引用(Variables Separation)_php技巧

首先我们回顾一下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脚本中的参数。
Statement
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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

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.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software