dongqian5384 2013-08-29 19:27
浏览 34
已采纳

理解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:

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.

  • 写回答

2条回答 默认 最新

  • duangang79177 2013-08-29 19:35
    关注

    Your code is evaluating like this:

    while (!($apns = ($this->getApns($streamContext) && ($z < 11))))
    

    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.

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog