PHP Logical Operators precedence affects variable assignment results strangely

$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!!


    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.


    && 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的AND&&操作符都是逻辑和,但是and版本的绑定优先级较低,请参阅:http://php.net/manual/en/language.operators.precedence.php

    链接地址: http://www.djcxy.com/p/10100.html

    上一篇: 显示所有错误和警告

    下一篇: PHP逻辑运算符优先级奇怪地影响变量赋值结果