PHP operator precedence “Undefined order of evaluation”?

前端 未结 3 771
不知归路
不知归路 2020-12-21 19:35

http://www.php.net/manual/en/language.operators.precedence.php#example-115


<
3条回答
  •  太阳男子
    2020-12-21 20:02

    Order of evaluation isn't a precedence issue. It has nothing to do with operators. The problem also happens with function calls.

    By the way, $a++ returns the old value of $a. In your example, $a++ evaluates to 1, not 2.

    In the following example, PHP does not define which subexpression is evaluated first: $a or $a++.

    $a = 1;
    f($a, $a++); //either f(1,1) or f(2,1)
    

    Precedence is about where you put in parentheses. Order of evaluation can't be changed by parentheses. To fix order of evaluation problems, you need to break the code up into multiple lines.

    $a = 1;
    $a0 = $a;
    $a1 = $a++;
    f($a0, $a1); //only f(1,1)
    

    Order of evaluation only matters when your subexpressions can have side-effects on each other: the value of one subexpression can change if another subexpression is evaluated first.

提交回复
热议问题