$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);
}
- 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?
- 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!!
- 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!!
&& 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.
&&
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.
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
来源:https://stackoverflow.com/questions/8898108/php-logical-operators-precedence-affects-variable-assignment-results-strangely