Home Backend Development PHP Tutorial 分析PHP内核中是如何实现 empty, isset 这些函数的

分析PHP内核中是如何实现 empty, isset 这些函数的

Jun 23, 2016 pm 01:23 PM

#### 叨叨几句本来这个问题是在oschina上提出的:  <http://www.oschina.net/question/1179015_2140695>但一直没收到合适的答案,所以还是自己下功夫梳理了一下,如果有错误的地方,欢迎交流。通常的函数是通过ZEND_FUNCTION(xxx) 这种宏定义来实现的,这个规范很好理解,也很容易读懂源码。但empty(), isset() 准确的说不是函数,但PHP的Manual还是称之函数,类似的还有echo, eval等。#### 准备工作用于查看PHP的扩展vld,下载:  <http://pecl.php.net/package/vld>PHP源码,分支 => remotes/origin/PHP-5.6.14	git clone http://git.php.net/repository/php-src.git -b PHP-5.6.14PHP opcode对应参考:  <http://php.net/manual/en/internals2.opcodes.php>> PHP执行程序版本为 5.6.14 ,其他版本opcode可能会有细微差别。PHP 内核源码分析:  <http://www.php-internals.com/book/>#### 开始分析示例代码 vld.php :	<?php		$a = 0;		empty($a);		isset($a);通过vld 查看opcode ,`php -d vld.active=1 vld.php`	number of ops:  10	compiled vars:  !0 = $a	line     #* E I O op                           fetch          ext  return  operands	-------------------------------------------------------------------------------------	   2     0  E >   EXT_STMT			 1        ASSIGN                                                   !0, 0	   3     2        EXT_STMT			 3        ISSET_ISEMPTY_VAR                           293601280  ~1      !0			 4        FREE                                                     ~1	   4     5        EXT_STMT			 6        ISSET_ISEMPTY_VAR                           310378496  ~2      !0			 7        FREE                                                     ~2	   6     8        EXT_STMT			 9      > RETURN                                                   1	branch: #  0; line:     2-    6; sop:     0; eop:     9; out1:  -2opcode中都出现了ZEND_ISSET_ISEMPTY_VAR,我们一步步分析。当执行PHP源码,会先进行语法分析,empty, isset的yacc如下:vim Zend/zend_language_parser.y +1265	1265 internal_functions_in_yacc:	1266 ›   ›   T_ISSET '(' isset_variables ')' { $$ = $3; }	1267 ›   |›  T_EMPTY '(' variable ')'›   { zend_do_isset_or_isempty(ZEND_ISEMPTY, &$$, &$3 TSRMLS_CC); }	1275	1276 isset_variables:	1277 ›   ›   isset_variable› ›   ›   { $$ = $1; }	1280	1281 isset_variable:	1282 ›   ›   variable›   ›   ›   ›   { zend_do_isset_or_isempty(ZEND_ISSET, &$$, &$1 TSRMLS_CC); }最终都执行了zend_do_isset_or_isempty,继续查找:	git grep -in "zend_do_isset_or_isempty"	Zend/zend_compile.c:6287:void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {:{:{ */vi Zend/zend_compile.c +6287	6287 void zend_do_isset_or_isempty(int type, znode *result, znode *variable TSRMLS_DC) /* {{{ */	6288 {	6289 ›   zend_op *last_op;	6290	6291 ›   zend_do_end_variable_parse(variable, BP_VAR_IS, 0 TSRMLS_CC);	6292	6293 ›   if (zend_is_function_or_method_call(variable)) {	6294 ›   ›   if (type == ZEND_ISEMPTY) {	6295 ›   ›   ›   /* empty(func()) can be transformed to !func() */	6296 ›   ›   ›   zend_do_unary_op(ZEND_BOOL_NOT, result, variable TSRMLS_CC);	6297 ›   ›   } else {	6298 ›   ›   ›   zend_error_noreturn(E_COMPILE_ERROR, "Cannot use isset() on the result of a function call (you can use \"null !== func()\" instead)");	6299 ›   ›   }	6300	6301 ›   ›   return;	6302 ›   }	6303	6304 ›   if (variable->op_type == IS_CV) {	6305 ›   ›   last_op = get_next_op(CG(active_op_array) TSRMLS_CC);	6306 ›   ›   last_op->opcode = ZEND_ISSET_ISEMPTY_VAR;最后一行 6306,ZEND_ISSET_ISEMPTY_VAR 这个opcode 出来了,IS_CV 判断参数是否为变量。注意zend_is_function_or_method_call(variable),当isset(fun($a)),函数参数写法会报错,empty在5.5版本开始支持函数参数,低版本不支持。opcode 是由 zend_execute 执行的,最终会对应处理函数的查找,这个是核心,请参阅:  <http://www.php-internals.com/book/?p=chapt02/02-03-03-from-opcode-to-handler>opcode 对应处理函数的命名规律:	ZEND_[opcode]_SPEC_(变量类型1)_(变量类型2)_HANDLER变量类型1和变量类型2是可选的,如果同时存在,那就是左值和右值,归纳有下几类: VAR TMP CV UNUSED CONST 这样可以根据相关的执行场景来判定。所以 ZEND_ISSET_ISEMPTY_VAR 对应的handler如下:	Zend/zend_vm_execute.h:44233:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CONST_CONST_HANDLER,	Zend/zend_vm_execute.h:44235:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CONST_VAR_HANDLER,	Zend/zend_vm_execute.h:44236:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CONST_UNUSED_HANDLER,	Zend/zend_vm_execute.h:44238:   ZEND_ISSET_ISEMPTY_VAR_SPEC_TMP_CONST_HANDLER,	Zend/zend_vm_execute.h:44240:   ZEND_ISSET_ISEMPTY_VAR_SPEC_TMP_VAR_HANDLER,	Zend/zend_vm_execute.h:44241:   ZEND_ISSET_ISEMPTY_VAR_SPEC_TMP_UNUSED_HANDLER,	Zend/zend_vm_execute.h:44243:   ZEND_ISSET_ISEMPTY_VAR_SPEC_VAR_CONST_HANDLER,	Zend/zend_vm_execute.h:44245:   ZEND_ISSET_ISEMPTY_VAR_SPEC_VAR_VAR_HANDLER,	Zend/zend_vm_execute.h:44246:   ZEND_ISSET_ISEMPTY_VAR_SPEC_VAR_UNUSED_HANDLER,	Zend/zend_vm_execute.h:44253:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CV_CONST_HANDLER,	Zend/zend_vm_execute.h:44255:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CV_VAR_HANDLER,	Zend/zend_vm_execute.h:44256:   ZEND_ISSET_ISEMPTY_VAR_SPEC_CV_UNUSED_HANDLER,我们看下 ZEND_ISSET_ISEMPTY_VAR_SPEC_CV_VAR_HANDLER 这个处理函数:vim Zend/zend_vm_execute.h +37946	38013 ›   if (opline->extended_value & ZEND_ISSET) {	38014 ›   ›   if (isset && Z_TYPE_PP(value) != IS_NULL) {	38015 ›   ›   ›   ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 1);	38016 ›   ›   } else {	38017 ›   ›   ›   ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 0);	38018 ›   ›   }	38019 ›   } else /* if (opline->extended_value & ZEND_ISEMPTY) */ {	38020 ›   ›   if (!isset || !i_zend_is_true(*value)) {	38021 ›   ›   ›   ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 1);	38022 ›   ›   } else {	38023 ›   ›   ›   ZVAL_BOOL(&EX_T(opline->result.var).tmp_var, 0);	38024 ›   ›   }上面的 if ... else 就是判断是isset,还是empty,然后做不同处理,Z_TYPE_PP, i_zend_is_true 不同判断。echo 等处理类似,自己按照流程具体去分析。关键是根据映射表找到对应的handler处理函数。了解这些处理流程后,相信会对PHP语句的性能分析更熟悉。原文出自[老刺猬](http://www.yinqisen.cn),<http://www.yinqisen.cn/blog-680.html>
Copy after login

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

Video Face Swap

Video Face Swap

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

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

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...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles