PHP operator precedence “Undefined order of evaluation”?

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

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


<
3条回答
  •  自闭症患者
    2020-12-21 20:19

    Operator precedence in PHP is a mess, and it's liable to change between versions. For that reason, it's always best to use parentheses to group your in-line equations so that there is no ambiguity in their execution.

    The example I usually give when asked this question is to ask in turn what the answer to this equation would be:

    $a = 2;
    $b = 4;
    $c = 6;
    $val = $a++ + ++$b - 0 - $c - -++$a;
    
    echo $val;
    

    :)

    Depending where I run it now, I get anything between 4 and 7, or a parser error.

    This will load $a (1) into memory, then load it into memory again and increment it (1 + 1), then it will add the two together, giving you 3:

    $a = 1;
    $val = $a + ($a++);
    

    This, however, is a parser error:

    $a = 1;
    $val = ($a + $a)++;
    

    Anyway, long story short, your example 2) is the way that most versions will interpret it unless you add parenthesis around ($a++) as in the example above, which will make it run the same way in all PHP versions that support the incrementation operator. :)

提交回复
热议问题