PHP Logical Operators precedence affects variable

2019-03-05 15:43发布

问题:

$var4 = 123;

function fn1($p1)
{
    return array('p1' => 1, 'p2' => 2);
}

if ($var1 = fn1(1) AND $var4 == 123)
{
    print_r($var1);
}

if ($var2 = fn1(1) && $var4 == 123)
{
    print_r($var2);
}

if (($var3 = fn1(1)) && $var4 == 123)
{
    print_r($var3);
}
  1. If you run this simple script it will output strange results, at least for me!! First output from first if expression will result in an array returned from the function & assigned to the $var1 variable, which is what I'm expecting, well?
  2. Second output from second if expression will result in an integer '1' assigned to the $var2 variable, which is NOT expected at all!! Please note that the only changed thing is the logical operator, I've used '&&' rather than 'AND', that's all!!
  3. Third output from third if expression will result again the expected array returned from the function & assigned to the $var3 variable, exactly as the first if expression, but wait: I've just embraced the assignment statement in the if expression within brackets, while still using the second if expression code!!

Can anyone explain technically -in details- why this strange behavior? php.net reference links will be appreciated.

I know that '&&' has higher precedence than 'AND' but that doesn't explains it to me!!

回答1:

PHP: Operator Precendence

&& has a higher precedence than =, so in the second if, you are assigning the value of fn1(1) && $var4 == 123 (true or false) to $var2.

In the first if, AND has a lower precedence than =, so the assignment happens first, then the result is compared.

In the third if, the assignment happens first again because everything in parens gets processed first.



回答2:

&& has a higher precedence than =, so what's really happening is something more like:

if ($var1 = (fn(1) && $var4 == 123))

So what is really being assigned to $var1 is the boolean result, which is why you get 1.



回答3:

PHP's AND and && operators both are logical ands, but the and version has a lower binding precedence, see: http://php.net/manual/en/language.operators.precedence.php