Understanding operator precedence in php

后端 未结 2 754
遥遥无期
遥遥无期 2021-01-18 15:18

I have the following code in production that appears to be causing an infinite loop.

 $z=1;
 while (!$apns = $this->getApns($streamContext) && $z          


        
2条回答
  •  滥情空心
    2021-01-18 15:59

    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);
    }
    

提交回复
热议问题