PHP kernel exploration variable Zval
We already know that PHP variables are actually implemented through the zval structure in the kernel, and we also have a preliminary understanding of how to set the type and value of a zval structure.
When coding, we hope that the zval created in the kernel can be used by users as variables in the PHP language. In order to achieve this function, we must first create a zval. The easiest way to think of is to create a zval pointer, then allocate a piece of memory and let the pointer point to it. If the shadow of malloc(sizeof(zval)) appears in your mind, then please stop immediately and don't use malloc to do this. The kernel provides us with corresponding macros to handle this. The reason is the same as before. : In order to make the code beautiful and maintain compatibility during version upgrades. This macro is: MAKE_STD_ZVAL(pzv). This macro will use the kernel method to apply for a piece of memory and pay its address to pzv, and initialize its two attributes refcount and is_ref. What's even better is that it will not only automatically handle the problem of insufficient memory, but also select the memory in the memory. The best place to apply.
As a container of data, we often need to deal with variables, whether they are numbers, arrays, strings, objects or others. Therefore, it can be said that variables are an indispensable foundation for language. This article is the first article on variables explored in the PHP kernel. It mainly introduces the basic knowledge of zval, including the following aspects:
- Basic structure of Zval
- Methods to view zval: debug_zval_dump and xdebug
- Zval’s principle, COW, etc.
Due to the rush of writing, there will inevitably be errors, please point them out.
1. Basic structure of Zval
Zval is one of the most important data structures in PHP (another important data structure is hash table). It contains information about variable values and types in PHP. It is a struct, the basic structure is:
<span>struct</span><span> _zval_struct { zvalue_value value; </span><span>/*</span><span> value </span><span>*/</span><span> zend_uint refcount__gc; </span><span>/*</span><span> variable ref count </span><span>*/</span><span> zend_uchar type; </span><span>/*</span><span> active type </span><span>*/</span><span> zend_uchar is_ref__gc; </span><span>/*</span><span> if it is a ref variable </span><span>*/</span><span> }; typedef </span><span>struct</span> _zval_struct zval;
Among them:
1. zval_value value
The actual value of the variable, specifically a union of zvalue_value:
<span>typedef union _zvalue_value { </span><span>long</span> lval; <span>/*</span><span> long value </span><span>*/</span> <span>double</span> dval; <span>/*</span><span> double value </span><span>*/</span> <span>struct</span> { <span>/*</span><span> string </span><span>*/</span> <span>char</span> *<span>val; </span><span>int</span><span> len; } str; HashTable </span>*ht; <span>/*</span><span> hash table value,used for array </span><span>*/</span><span> zend_object_value obj; </span><span>/*</span><span> object </span><span>*/</span><span> } zvalue_value;</span>
2. zend_uint refcount__gc
This value is actually a counter to save how many variables (or symbols, symbols) there are. All symbols are stored in the symbol table. Different scopes use different symbol tables. Regarding this, We'll discuss this later) points to the zval. When a variable is generated, its refcount=1. Typical assignment operations such as $a = $b will increase the refcount of zval by 1, and the unset operation will decrease it by 1 accordingly. Before PHP5.3, the reference counting mechanism was used to implement GC. If the refcount of a zval was less than 0, the Zend engine would think that there was no variable pointing to the zval, and therefore would release the memory space occupied by the zval. But, sometimes things are not that simple. We will see later that the simple reference counting mechanism cannot GC the circularly referenced zval, even if the variable pointing to the zval has been unset, resulting in a memory leak (Memory Leak).
3. zend_uchar type
This field is used to indicate the actual type of the variable. When we started learning PHP, we already knew that variables in PHP include four scalar types(bool, int, float, string), two composite types(array, object) and two special types (resource and NULL). Inside zend, these types correspond to the following macros (code location phpsrc/Zend/zend.h):
<span>#define</span> IS_NULL 0 <span>#define</span> IS_LONG 1 <span>#define</span> IS_DOUBLE 2 <span>#define</span> IS_BOOL 3 <span>#define</span> IS_ARRAY 4 <span>#define</span> IS_OBJECT 5 <span>#define</span> IS_STRING 6 <span>#define</span> IS_RESOURCE 7 <span>#define</span> IS_CONSTANT 8 <span>#define</span> IS_CONSTANT_ARRAY 9 <span>#define</span> IS_CALLABLE 10
4. is_ref__gc
This field is used to mark whether the variable is a reference variable. For ordinary variables, the value is 0, and for reference variables, the value is 1. This variable will affect the sharing, separation, etc. of zval. We will discuss this later.
As the name suggests, ref_count__gc and is_ref__gc are two very important fields required by PHP's GC mechanism. The values of these two fields can be viewed through debugging tools such as xdebug.
2. Installation and configuration of xdebug
Xdebug is an open source PHP performance analysis and debugging tool. Although for general program debugging, var_dump, echo, print, debug_backtrace and other common debugging tools are basically enough, for some complex debugging and performance testing, xdebug is definitely a good helper (others Tools such as Xhprof are also excellent).
Basic environment of this article:
The basic process of installing Xdebug is (actually compiling an extension from source code):
1. Download the source code package.
The download address is: http://www.xdebug.org/docs/install
本文中下载的版本为:Xdebug-2.6.tar.gz
2. 解压
<span>tar</span> xvzf xdebug-<span>2.6</span>.<span>tar</span>.gz
3. 在xdebug的目录执行phpize
4. ./configure 配置
5. Make&& make install
这会生成xdebug.so扩展文件(zend_extension),位置在xdebug/modules
6. 在php.ini中加载xdebug扩展
zend_extension=your-xdebug-path/xdebug.so
7. 添加xdebug的配置
xdebug.profiler_enable =<span> on xdebug.default_enable </span>=<span> on xdebug.trace_output_dir</span>="/tmp/xdebug"<span> xdebug.trace_output_name </span>=<span> trace.%c.%p xdebug.profiler_output_dir</span>="/tmp/xdebug"<span> xdebug.profiler_output_name</span>="cachegrind.out.%s"
这里不再详细介绍各个配置项的含义,详细的请看:http://www.xdebug.org/docs/all
现在,PHP中,应该已经有了Xdebug的扩展信息(php –m,也可以phpinfo()):
在Xdebug中,可以通过xdebug_debug_zval打印Zval的信息:
<?php $a = array( 'test' ); $a[] = &$a; xdebug_debug_zval( 'a' );
3. Zval的更多原理
(注,本部分主要参考:http://derickrethans.nl/collecting-garbage-phps-take-on-variables.html, 作者Derick Rethans是一位优秀的PHP内核专家,在全世界做过多次报告,都有相关的pdf下载,这里(http://derickrethans.nl/talks.html )有作者每次演讲的记录,很多都值得我们深入去学习研究)
前面我们已经说过,PHP使用Zval这种结构来保存变量,这里我们将继续追踪zval的更多细节。
1. 创建变量时,会创建一个zval.
$str = "test zval"; xdebug_debug_zval('str');
输出结果:
str: (refcount=1, is_ref=0)='test zval'
当使用$str="test zval";来创建变量时,会在当前作用域的符号表中插入新的符号(str),由于该变量是一个普通的变量,因此会生成一个refcount=1且is_ref=0的zval容器。也就是说,实际上是这样的:
2. 变量赋值给另外一个变量时,会增加zval的refcount值。
$str = "test zval"; $str2 = $str; xdebug_debug_zval('str'); xdebug_debug_zval('str2');
输出结果:
str: (refcount=2, is_ref=0)=<span>'test zval' str2: (refcount</span>=2, is_ref=0)='test zval'
同时我们看到,str和是str2这两个symbol的zval结构是一样的。这里其实是PHP所做的一个优化,由于str和str2都是普通变量,因而它们指向了同一个zval,而没有为str2开辟单独的zval。这么做,可以在一定程度上节省内存。这时的str,str2与zval的对应关系是这样的:
3. 使用unset时,对减少相应zval的refcount值
$str = "test zval"; $str3 = $str2 = $str; xdebug_debug_zval('str'); unset($str2,$str3) xdebug_debug_zval('str');
结果为:
str: (refcount=3, is_ref=0)=<span>'test zval' str: (refcount</span>=1, is_ref=0)='test zval'
由于unset($str2,$str3)会将str2和str3从符号表中删除,因此,在unset之后,只有str指向该zval,如下图所示:
现在如果执行unset($str),则由于zval的refcount会减少到0,该zval会从内存中清理。这当然是最理想的情况。
但是事情并不总是那么乐观。
4. 数组变量与普通变量生成的zval非常类似,单也有很大不同
与标量这些普通变量不同,数组和对象这类复合型的变量在生成zval时,会为每个item项生成一个zval容器。例如:
$ar = array( 'id' => 38, 'name' => 'shine' ); <span>xdebug_debug_zval('ar');</span>
打印出zval的结构是:
ar: (refcount=1, is_ref=0)=<span>array ( 'id' </span>=> (refcount=1, is_ref=0)=38,<span> 'name' </span>=> (refcount=1, is_ref=0)=<span>'shine' )</span>
如下图所示:
可以看出,变量$ar生成的过程中,共生成了3个zval容器(红色部分标注)。对于每个zval而言,refcount的增减规则与普通变量的相同。例如,我们在数组中添加另外一个元素,并把$ar['name']的值赋给它:
$ar = array( 'id' => 38, 'name' => 'shine' ); $ar['test'] = $ar['name']; xdebug_debug_zval('ar');
则打印出的zval为:
ar: (refcount=1, is_ref=0)=<span>array ( 'id' </span>=> (refcount=1, is_ref=0)=38,<span> 'name' </span>=> (refcount=2, is_ref=0)='shine',<span> 'test' </span>=> (refcount=2, is_ref=0)=<span>'shine' )</span>
如同普通变量一样,这时候,name和test这两个symbol指向同一个zval:
同样的,从数组中移除元素时,会从符号表中删除相应的符号,同时减少对应zval的refcount值。同样,如果zval的refcount值减少到0,那么就会从内存中删除该zval:
$ar = array( 'id' => 38, 'name' => 'shine' ); $ar['test'] = $ar['name']; unset($ar['test'],$ar['name']); xdebug_debug_zval('ar');
输出结果为:
ar: (refcount=1, is_ref=0)=array ('id' => (refcount=1, is_ref=0)=38)
5. 引用的出现,会令zval的规则变得复杂
在加入引用之后,情况会变的稍微复杂一点。例如,在数组中添加对本身的引用:
$a = $array('one'); $a[] = &$a; xdebug_debug_zval('a');
输出的结果:
a: (refcount=2, is_ref=1)=<span>array ( </span>0 => (refcount=1, is_ref=0)='one', 1 => (refcount=2, is_ref=1)=<span>... )</span>
上述输出中,…表示指向原始数组,因而这是一个循环的引用。如下图所示:
现在,我们对$a执行unset操作,这会在symbol table中删除相应的symbol,同时,zval的refcount减1(之前为2),也就是说,现在的zval应该是这样的结构:
(refcount=1, is_ref=1)=<span>array ( </span>0 => (refcount=1, is_ref=0)='one', 1 => (refcount=1, is_ref=1)=<span>... )</span>
也就是下图所示的结构:
这时,不幸的事情发生了!
Unset之后,虽然没有变量指向该zval,但是该zval却不能被GC(指PHP5.3之前的单纯引用计数机制的GC)清理掉,因为zval的refcount均大于0。这样,这些zval实际上会一直存在内存中,直到请求结束(参考SAPI的生命周期)。在此之前,这些zval占据的内存不能被使用,便白白浪费了,换句话说,无法释放的内存导致了内存泄露。
如果这种内存泄露仅仅发生了一次或者少数几次,倒也还好,但如果是成千上万次的内存泄露,便是很大的问题了。尤其在长时间运行的脚本中(例如守护程序,一直在后台执行不会中断),由于无法回收内存,最终会导致系统“再无内存可用”。
6. zval分离(Copy on write和change on write)
前面我们已经介绍过,在变量赋值的过程中例如$b = $a,为了节省空间,并不会为$a和$b都开辟单独的zval,而是使用共享zval的形式:
那么问题来了:如果其中一个变量发生变化时,如何处理zval的共享问题?
对于这样的代码:
$a = "a simple test"; $b = $a; echo "before write:".PHP_EOL; xdebug_debug_zval('a'); xdebug_debug_zval('b'); $b = "thss"; echo "after write:".PHP_EOL; xdebug_debug_zval('a'); xdebug_debug_zval('b');
打印的结果是:
<span>before write: a: (refcount</span>=2, is_ref=0)=<span>'a simple test' b: (refcount</span>=2, is_ref=0)=<span>'a simple test' after write: a: (refcount</span>=1, is_ref=0)=<span>'a simple test' b: (refcount</span>=1, is_ref=0)='thss'
起初,符号表中a和b指向了同一个zval(这么做的原因是节省内存),而后$b发生了变化,Zend会检查b指向的zval的refcount是否为1,如果是1,那么说明只有一个符号指向该zval,则直接更改zval。否则,说明这是一个共享的zval,需要将该zval分离出去,以保证单独变化互不影响,这种机制叫做COW –Copy on write。在很多场景下,COW都是一种比较高效的策略。
那么对于引用变量呢?
$a = 'test'; $b = &$a; echo "before change:".PHP_EOL; xdebug_debug_zval('a'); xdebug_debug_zval('b'); $b = 12; echo "after change:".PHP_EOL; xdebug_debug_zval('a'); xdebug_debug_zval('b'); unset($b); echo "after unset:".PHP_EOL; xdebug_debug_zval('a'); xdebug_debug_zval('b');
输出的结果为:
<span>before change: a: (refcount</span>=2, is_ref=1)=<span>'test' b: (refcount</span>=2, is_ref=1)=<span>'test' after change: a: (refcount</span>=2, is_ref=1)=12<span> b: (refcount</span>=2, is_ref=1)=12<span> after unset: a: (refcount</span>=1, is_ref=0)=12
可以看出,在改变了$b的值之后,Zend会检查zval的is_ref检查是否是引用变量,如果是引用变量,则直接更改即可,否则,需要执行刚刚提到的zval分离。由于$a 和 $b是引用变量,因而更改共享的zval实际上也间接更改了$a的值。而在unset($b)之后,变量$b从符号表中删除了。
这里也说明一个问题,unset并不是清除zval,而只是从符号表中删除相应的symbol。这样一来,之前很多的关于引用的疑问也可以理解了(下一节我们将深入探索PHP的引用)。
以上就介绍了PHP内核探索之变量Zval,包括了变量Zval方面的内容,希望对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

AI Hentai Generator
Generate AI Hentai for free.

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



The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

Do you see "A problem occurred" along with the "OOBELANGUAGE" statement on the Windows Installer page? The installation of Windows sometimes stops due to such errors. OOBE means out-of-the-box experience. As the error message indicates, this is an issue related to OOBE language selection. There is nothing to worry about, you can solve this problem with nifty registry editing from the OOBE screen itself. Quick Fix – 1. Click the “Retry” button at the bottom of the OOBE app. This will continue the process without further hiccups. 2. Use the power button to force shut down the system. After the system restarts, OOBE should continue. 3. Disconnect the system from the Internet. Complete all aspects of OOBE in offline mode

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

The activation process on Windows sometimes takes a sudden turn to display an error message containing this error code 0xc004f069. Although the activation process is online, some older systems running Windows Server may experience this issue. Go through these initial checks, and if they don't help you activate your system, jump to the main solution to resolve the issue. Workaround – close the error message and activation window. Then restart the computer. Retry the Windows activation process from scratch again. Fix 1 – Activate from Terminal Activate Windows Server Edition system from cmd terminal. Stage – 1 Check Windows Server Version You have to check which type of W you are using
