dongrong5189 2012-01-17 16:24
浏览 55
已采纳

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

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

  • 写回答

3条回答 默认 最新

  • dongyong2906 2012-01-17 16:30
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用