PHP运算符优先级为“未定义的评估顺序"? [英] PHP operator precedence "Undefined order of evaluation"?
问题描述
http://www.php.net/manual/zh-CN/language.operators.precedence.php#example-115
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3
?>
php手册中的示例不能很好地解释.为什么不将$a++
评估为2
,然后又将其添加到1
,以使其始终成为echo 1 + 2 // equals 3
?我不明白它可能打印2或3"的方式.我认为增量++
的优先级比加法+
的优先级高?
The example from the php manual doesn't explain very well. Why isn't $a++
evaluated to 2
, and then added to 1
, so that it always becomes echo 1 + 2 // equals 3
? I don't understand how it "may print either 2 or 3". I thought incremental ++
has "higher precedence" than addition +
?
换句话说,我不明白为什么不是...
In other words, I don't understand why isn't it...
$a = 1;
1) echo $a + $a++;
2) echo 1 + ($a = 1 + 1);
3) echo 1 + (2);
4) echo 3;
推荐答案
PHP中的运算符优先级是一团糟,并且很容易在版本之间进行更改.因此,最好使用括号对内联方程进行分组,以免执行时含糊不清.
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;
:)
根据我现在在哪里运行,我会得到4到7之间的任何值,或者解析器错误.
Depending where I run it now, I get anything between 4 and 7, or a parser error.
这会将$ a(1)加载到内存中,然后再次将其加载到内存中 并递增(1 + 1),然后将两者加在一起,得到3:>
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)++;
总之,长话短说,您的示例2)
是大多数版本将解释它的方式,除非像上面的示例中在($a++)
周围加上括号,这将使其在所有PHP版本中以相同的方式运行支持增量运算符. :)
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. :)
这篇关于PHP运算符优先级为“未定义的评估顺序"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!