Understanding operator priority in php

I have the following code in production that causes 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 priority rules that cause this behavior applied?

http://php.net/manual/en/language.operators.precedence.php

I see this note in the docs:

Although = has a lower priority than most other operators, PHP will still allow expressions like the following: if (! $ A = foo ()), in which case the return value of foo () is placed in $ a.

Which makes me think that you first need to evaluate value =. then! then & &, which will not cause an infinite loop.

+6
source share
2 answers

Your code is evaluated as follows:

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

therefore you see an infinite loop (as soon as $z >= 11 , $apns is false, so the condition is always true). The reason for this priority is that special rules only apply to ! to the left of an assignment with a lower priority than = ). It does not affect the logical operator on the right, which behaves as in any normal language.

Your style is bad. Try this, which is much readable and differs only in the final value of $z (and if it is important, you can configure 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); } 
+2
source

Your code is a prime example of why itโ€™s a good habit to always put all conditions in parentheses (and the same goes for a block of code. Even oneliners should be surrounded by { and } ). So, instead of vulnerability:

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

do

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

and you will be safe.

+2
source

Source: https://habr.com/ru/post/952775/


All Articles