了解php中的运算符优先级 [英] Understanding operator precedence in php
问题描述
我在生产中有以下代码似乎正在引起无限循环.
I have the following code in production that appears to be causing an infinite loop.
$z=1;
while (!$apns = $this->getApns($streamContext) && $z < 11)
{
myerror_log("unable to conncect to apple. sleep for 2 seconds and try again");
$z++;
sleep(2);
}
如何应用导致此行为的优先规则?
How are the precedence rules getting applied that cause this behavior?
http://php.net/manual/en/language.operators.precedence.php
我在文档中看到此注释:
I see this note in the docs:
尽管=的优先级低于大多数其他运算符,但PHP会 仍然允许类似于以下内容的表达式:if(!$ a = foo()),在 在这种情况下,foo()的返回值放入$ a中.
Although = has a lower precedence than most other operators, PHP will still allow expressions similar to the following: if (!$a = foo()), in which case the return value of foo() is put into $a.
这使我认为= =应该首先被评估.然后!然后是&& ;,这不会导致无限循环.
Which makes me think the the = should be evaluated first. then the ! then the &&, which would not cause an infinite loop.
推荐答案
您的代码正在这样评估:
Your code is evaluating like this:
while (!($apns = ($this->getApns($streamContext) && ($z < 11))))
这就是为什么您看到无限循环的原因($z >= 11
,$apns
为假,因此条件始终为true).此优先级的原因是,特殊规则仅适用于有效分配的左上的!
(优先级低于=
).它对右侧的布尔运算符没有影响,布尔运算符的行为与任何理智的语言相同.
which is why you see the infinite loop (as soon as $z >= 11
, $apns
is false, so the condition is always true). The reason for this precedence is that the special rules only apply to !
on the left of the assignment being valid (having lower precedence than =
). It has no effect on the boolean operator on the right, which behaves as it would in any sane language.
您的风格不好.试试看,它更易读,只是最终值$z
不同(如果很重要,您可以调整break
语句.
Your style is bad. Try this, which is much more readable and only differs in the final value of $z
(and if that's important you can tweak the break
statement.
for( $z = 1; $z < 11; ++ $z ) {
// note extra brackets to make it clear that we intend to do assignment not comparison
if( ($apns = $this->getApns($streamContext)) ) {
break;
}
myerror_log("unable to conncect to apple. sleep for 2 seconds and try again");
sleep(2);
}
这篇关于了解php中的运算符优先级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!