Press "Enter" to skip to content

深入理解PHP原理之foreach

foreach是PHP中很常用的一个用作数组循环的控制语句。
因为它的方便和易用,自然也就在后端隐藏着很复杂的具体实现方式(对用户透明)
今天,我们就来一起分析分析,foreach是如何实现数组(对象)的遍历的。
本节内容涉及到较多编译原理(lex and yacc)的知识,所以如果您觉得看不太懂,可以先找相关的资料看看。

我们知道PHP是一个脚本语言,也就是说,用户编写的PHP代码最终都是会被PHP解释器解释执行,
特别的,对于PHP来说,所有的用户编写的PHP代码,都会被翻译成PHP的虚拟机ZE的虚拟指令(OPCODES)来执行(参看:深入理解PHP原理之Opcodes).

不论细节的话,就是说,我们所编写的任何PHP脚本,都会最终被翻译成一条条的指令,从而根据指令,由相应的C编写的函数来执行。

那么foreach会被翻译成什么样子呢?

foreach($arr as $key => $val){
	echo $key . '=>' . $val . "\n";
}

在词法分析阶段,foreach会被识别为一个TOKEN:T_FOREACH,
在语法分析阶段,会被规则:

  unticked_statement:  //没有被绑定ticks的语句
	//有省略
    |   T_FOREACH '(' variable T_AS
        { zend_do_foreach_begin(&$1, &$2, &$3, &$4, 1 TSRMLS_CC); }
        foreach_variable foreach_optional_arg ')' { zend_do_foreach_cont(&$1, &$2, &$4, &$6, &$7 TSRMLS_CC); }
        foreach_statement { zend_do_foreach_end(&$1, &$4 TSRMLS_CC); }
    |   T_FOREACH '(' expr_without_variable T_AS
        { zend_do_foreach_begin(&$1, &$2, &$3, &$4, 0 TSRMLS_CC); }
        variable foreach_optional_arg ')' { zend_check_writable_variable(&$6); zend_do_foreach_cont(&$1, &$2, &$4, &$6, &$7 TSRMLS_CC); }
        foreach_statement { zend_do_foreach_end(&$1, &$4 TSRMLS_CC); }
	//有省略
;

仔细分析这段语法规则,我们可以发现,对于:
foreach($arr as $key => $val){
echo $key . '=>' . $val ."\n";
}
会被分析为:

	T_FOREACH '(' variable T_AS   { zend_do_foreach_begin('foreach', '(', $arr, 'as', 1 TSRMLS_CC); }
    foreach_variable  foreach_optional_arg(T_DOUBLE_ARROW  foreach_variable)   ')'  { zend_do_foreach_cont('foreach', '(', 'as', $key, $val TSRMLS_CC); }
    foreach_satement {zend_do_foreach_end('foreach', 'as');}

然后,让我们来看看foreach_statement:
它其实就是一个代码块,体现了我们的 echo $key . '=>' . $val ."\n";
T_ECHO expr;
显然,实现foreach的核心就是如下3个函数:
zend_do_foreach_begin
zend_do_foreach_cont
zend_do_foreach_end
其中,zend_do_foreach_begin (代码太长,直接写伪码) 主要做了:
1. 记录当前的opline行数(为以后跳转而记录)
2. 对数组进行RESET(讲内部指针指向第一个元素)
3. 获取临时变量 ($val)
4. 设置获取变量的OPCODE FE_FETCH,结果存第3步的临时变量
4. 记录获取变量的OPCODES的行数
而对于 zend_do_foreach_cont来说:
1. 根据foreach_variable的u.EA.type来判断是否引用
2. 根据是否引用来调整zend_do_foreach_begin中生成的FE_FETCH方式
3. 根据zend_do_foreach_begin中记录的取变量的OPCODES的行数,来初始化循环(主要处理在循环内部的循环:do_begin_loop)
最后zend_do_foreach_end:
1. 根据zend_do_foreach_begin中记录的行数信息,设置ZEND_JMP OPCODES
2. 根据当前行数,设置循环体下一条opline, 用以跳出循环
3. 结束循环(处理循环内循环:do_end_loop)
4. 清理临时变量
当然, 在zend_do_foreach_cont 和 zend_do_foreach_end之间 会在语法分析阶段被填充foreach_satement的语句代码。

这样,就实现了foreach的OPCODES line。
比如对于我们开头的实例代码,最终生成的OPCODES是:

filename:       /home/huixinchen/foreach.php
function name:  (null)
number of ops:  17
compiled vars:  !0 = $arr, !1 = $key, !2 = $val
line     #  op                           fetch          ext  return  operands
-------------------------------------------------------------------------------
   2     0  SEND_VAL                                                 1
         1  SEND_VAL                                                 100
         2  DO_FCALL                                      2          'range'
         3  ASSIGN                                                   !0, $0
   3     4  FE_RESET                                         $2      !0, ->14
         5  FE_FETCH                                         $3      $2, ->14
         6  ZEND_OP_DATA                                     ~5
         7  ASSIGN                                                   !2, $3
         8  ASSIGN                                                   !1, ~5
   4     9  CONCAT                                           ~7      !1, '-'
        10  CONCAT                                           ~8      ~7, !2
        11  CONCAT                                           ~9      ~8, '%0A'
        12  ECHO                                                     ~9
   5    13  JMP                                                      ->5
        14  SWITCH_FREE                                              $2
   7    15  RETURN                                                   1
        16* ZEND_HANDLE_EXCEPTION

我们注意到FE_FETCH的op2的操作数是14,也就是JMP后一条opline,也就是说,在获取完最后一个数组元素以后,FE_FETCH失败的情况下,会跳到第14行opline,从而实现了循环的结束。
而15行opline的op1的操作数是指向了FE_FETCH,也就是无条件跳转到第5行opline,从而实现了循环。

附录:

void zend_do_foreach_begin(znode *foreach_token, znode *open_brackets_token, znode *array, znode *as_token, int variable TSRMLS_DC)
{
    zend_op *opline;
    zend_bool is_variable;
    zend_bool push_container = 0;
    zend_op dummy_opline;
    if (variable) {
		//是否是匿名数组
        if (zend_is_function_or_method_call(array)) {
			//是否是函数返回值
            is_variable = 0;
        } else {
            is_variable = 1;
        }
        /* 使用括号记录FE_RESET的opline行数 */
        open_brackets_token->u.opline_num = get_next_op_number(CG(active_op_array));
        zend_do_end_variable_parse(BP_VAR_W, 0 TSRMLS_CC); //获取数组/对象和zend_do_begin_variable_parse对应
        if (CG(active_op_array)->last > 0 &&
            CG(active_op_array)->opcodes[CG(active_op_array)->last-1].opcode == ZEND_FETCH_OBJ_W) {
            /* Only lock the container if we are fetching from a real container and not $this */
            if (CG(active_op_array)->opcodes[CG(active_op_array)->last-1].op1.op_type == IS_VAR) {
                CG(active_op_array)->opcodes[CG(active_op_array)->last-1].extended_value |= ZEND_FETCH_ADD_LOCK;
                push_container = 1;
            }
        }
    } else {
        is_variable = 0;
        open_brackets_token->u.opline_num = get_next_op_number(CG(active_op_array));
    }
    foreach_token->u.opline_num = get_next_op_number(CG(active_op_array)); //记录数组Reset Opline number
    opline = get_next_op(CG(active_op_array) TSRMLS_CC); //生成Reset数组Opcode
    opline->opcode = ZEND_FE_RESET;
    opline->result.op_type = IS_VAR;
    opline->result.u.var = get_temporary_variable(CG(active_op_array));
    opline->op1 = *array;
    SET_UNUSED(opline->op2);
    opline->extended_value = is_variable ? ZEND_FE_RESET_VARIABLE : 0;
    dummy_opline.result = opline->result;
    if (push_container) {
        dummy_opline.op1 = CG(active_op_array)->opcodes[CG(active_op_array)->last-2].op1;
    } else {
        znode tmp;
        tmp.op_type = IS_UNUSED;
        dummy_opline.op1 = tmp;
    }
    zend_stack_push(&CG(foreach_copy_stack), (void *) &dummy_opline, sizeof(zend_op));
    as_token->u.opline_num = get_next_op_number(CG(active_op_array)); //记录循环起始点
    opline = get_next_op(CG(active_op_array) TSRMLS_CC);
    opline->opcode = ZEND_FE_FETCH;
    opline->result.op_type = IS_VAR;
    opline->result.u.var = get_temporary_variable(CG(active_op_array));
    opline->op1 = dummy_opline.result;    //被操作数组
    opline->extended_value = 0;
    SET_UNUSED(opline->op2);
    opline = get_next_op(CG(active_op_array) TSRMLS_CC);
    opline->opcode = ZEND_OP_DATA; //当使用key的时候附属操作数,当foreach中不包含key时忽略
    SET_UNUSED(opline->op1);
    SET_UNUSED(opline->op2);
    SET_UNUSED(opline->result);
}
void zend_do_foreach_cont(znode *foreach_token, const znode *open_brackets_token, const znode *as_token, znode *value, znode *key TSRMLS_DC)
{
    zend_op *opline;
    znode dummy, value_node;
    zend_bool assign_by_ref=0;
    opline = &CG(active_op_array)->opcodes[as_token->u.opline_num]; //获取FE_FETCH Opline
    if (key->op_type != IS_UNUSED) {
        znode *tmp;//交换key和val
        tmp = key;
        key = value;
        value = tmp;
        opline->extended_value |= ZEND_FE_FETCH_WITH_KEY; //表明需要同时获取key和val
    }
    if ((key->op_type != IS_UNUSED) && (key->u.EA.type & ZEND_PARSED_REFERENCE_VARIABLE)) {
		//key不能以引用方式获取
        zend_error(E_COMPILE_ERROR, "Key element cannot be a reference");
    }
    if (value->u.EA.type & ZEND_PARSED_REFERENCE_VARIABLE) {
		//以引用方式获取值
        assign_by_ref = 1;
        if (!(opline-1)->extended_value) {
			//根据FE_FETCH的上一条Opline也就是获取数组的扩展值来判断数组是否是匿名数组
            zend_error(E_COMPILE_ERROR, "Cannot create references to elements of a temporary array expression");
        }
        opline->extended_value |= ZEND_FE_FETCH_BYREF; //指明按引用取
        CG(active_op_array)->opcodes[foreach_token->u.opline_num].extended_value |= ZEND_FE_RESET_REFERENCE; //重置原数组
    } else {
        zend_op *foreach_copy;
        zend_op *fetch = &CG(active_op_array)->opcodes[foreach_token->u.opline_num];
        zend_op *end = &CG(active_op_array)->opcodes[open_brackets_token->u.opline_num];
        /* Change "write context" into "read context" */
        fetch->extended_value = 0;  /* reset ZEND_FE_RESET_VARIABLE */
        while (fetch != end) {
            --fetch;
            if (fetch->opcode == ZEND_FETCH_DIM_W && fetch->op2.op_type == IS_UNUSED) {
                zend_error(E_COMPILE_ERROR, "Cannot use [] for reading");
            }
            fetch->opcode -= 3; /* FETCH_W -> FETCH_R */
        }
        /* prevent double SWITCH_FREE */
        zend_stack_top(&CG(foreach_copy_stack), (void **) &foreach_copy);
        foreach_copy->op1.op_type = IS_UNUSED;
    }
    value_node = opline->result;
    if (assign_by_ref) {
        zend_do_end_variable_parse(value, BP_VAR_W, 0 TSRMLS_CC); //获取值(引用)
        zend_do_assign_ref(NULL, value, &value_node TSRMLS_CC);//指明value node的type是IS_VAR
    } else {
        zend_do_assign(&dummy, value, &value_node TSRMLS_CC); //获取copy值
        zend_do_free(&dummy TSRMLS_CC);
    }
    if (key->op_type != IS_UNUSED) {
        znode key_node;
        opline = &CG(active_op_array)->opcodes[as_token->u.opline_num+1];
        opline->result.op_type = IS_TMP_VAR;
        opline->result.u.EA.type = 0;
        opline->result.u.opline_num = get_temporary_variable(CG(active_op_array));
        key_node = opline->result;
        zend_do_assign(&dummy, key, &key_node TSRMLS_CC);
        zend_do_free(&dummy TSRMLS_CC);
    }
    do_begin_loop(TSRMLS_C);
    INC_BPC(CG(active_op_array));
}
void zend_do_foreach_end(znode *foreach_token, znode *as_token TSRMLS_DC)
{
    zend_op *container_ptr;
    zend_op *opline = get_next_op(CG(active_op_array) TSRMLS_CC); //生成JMP opcode
    opline->opcode = ZEND_JMP;
    opline->op1.u.opline_num = as_token->u.opline_num; //设置JMP到FE_FETCH opline行
    SET_UNUSED(opline->op1);
    SET_UNUSED(opline->op2);
    CG(active_op_array)->opcodes[foreach_token->u.opline_num].op2.u.opline_num = get_next_op_number(CG(active_op_array)); //设置跳出循环的opline行
    CG(active_op_array)->opcodes[as_token->u.opline_num].op2.u.opline_num = get_next_op_number(CG(active_op_array)); //同上
    do_end_loop(as_token->u.opline_num, 1 TSRMLS_CC); //为循环嵌套而设置
    zend_stack_top(&CG(foreach_copy_stack), (void **) &container_ptr);
    generate_free_foreach_copy(container_ptr TSRMLS_CC);
    zend_stack_del_top(&CG(foreach_copy_stack));
    DEC_BPC(CG(active_op_array)); //为PHP interactive模式而设置
}

21 Comments

  1. chris he
    chris he July 28, 2020

    底层的代码,厉害了

  2. […] 而foreach的实现,则位于 ./Zend/zend_compile.h ,在解释期被flex翻译成由 zend_do_foreach_begin zend_do_foreach_cont zend_do_foreach_end 这三个函数(以及相关代码)组合起来。由于看起来比较晦涩,我就不贴出来了(实际上我也没看太懂),详情可以参考雪候鸟的这篇:深入理解PHP原理之foreach最后附一段php代码的opcode<?php $arr = array(1,2,3); foreach ($arr as $x) echo $x; ?> […]

  3. Anonymous
    Anonymous January 24, 2013

    为什么在foreach中用continue的效果和break的效果是一样的呢,好奇怪的现象,我是php5.3版本的

  4. […] 深入理解PHP原理之foreach ⇐ ubuntu下源码安装 mysql 详细步骤 网友曝光微信密码漏洞 柳岩马化腾账号被入侵(图)(转) ⇒  相关文章 […]

  5. 斯人
    斯人 February 26, 2012

    好东西哦…
    学习了…研究中..

  6. Anonymous
    Anonymous March 12, 2011

    真垃圾 ,PHP,首先是烦人的声明变量的$
    为什么要这个,还有地些古老的符号->,=>,搞什么,

  7. xwz
    xwz February 21, 2011

    最近 用simplexml_load_file来获取xml,然后用个函数来foreach他,就是function aa($xml) {foreach($xml …
    嗯,得到了 死机的下场,特来学习下

  8. 蒋星星
    蒋星星 December 12, 2008

    虽然了解lex,但还是看不懂!
    佩服!!!

  9. 半醒
    半醒 December 9, 2008

    请问 为什么贵博的feed输出不是全文呢?
    可否修改下

  10. jackywdx
    jackywdx November 21, 2008

    呵呵,又有文章出来了.^_^

  11. ginux
    ginux November 21, 2008

    佩服

  12. blankyao
    blankyao November 20, 2008

    有点看不懂 🙁

    • 雪候鸟
      雪候鸟 November 21, 2008

      你也可以只关注最后的结论么,呵呵

Comments are closed.