PHP逻辑运算符的优先级会奇怪地影响变量分配结果 [英] PHP Logical Operators precedence affects variable assignment results strangely

查看:65
本文介绍了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. 如果运行此简单脚本,它将在以下位置输出奇怪的结果: 至少对我来说!如果表达式将导致第一个的第一个输出 从函数&返回的数组分配给$ var1 变量,这是我所期望的,好吗?
  2. 如果表达式将导致整数,则从第二个第二个输出 分配给$ var2变量的值为'1',这根本不是预期的!! 请注意,唯一更改的是逻辑运算符, 我用过'&&'而不是与",仅此而已!
  3. 如果表达式将再次产生预期的结果,则来自第三项的第三项输出 从函数&返回的数组分配给$ var3变量, 与第一个if表达式完全相同,但是请稍等:我刚刚接受了 方括号中的if表达式中的赋值语句,而 仍在使用第二个if表达式代码!

任何人都可以从技术上详细解释为什么这种奇怪的行为吗? php.net参考链接将不胜感激.

我知道&&"优先级比"AND"高,但这并不能向我解释!

解决方案

PHP:运算符的优势

&&的优先级比=高,因此在第二个if中,您将fn1(1) && $var4 == 123的值(真或假)分配给$ var2.

在第一个if中,AND的优先级低于=,因此首先进行赋值,然后比较结果.

在第三种情况下,该赋值首先发生,因为parens中的所有内容都首先得到处理.

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

解决方案

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.

这篇关于PHP逻辑运算符的优先级会奇怪地影响变量分配结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆