【问题标题】:Have I fundamentally misunderstood how PHP/C-like programming languages work? [duplicate]我是否从根本上误解了类 PHP/C 编程语言的工作原理? [复制]
【发布时间】:2020-01-17 01:39:56
【问题描述】:

看看这段代码:

if ($the_string = a_function_call('someid123') && $another_string = another_function_call('someid123'))
{
    // $the_string and $another_string are now both expected to be the values returned from their respective functions, and this block of code is expected to be run if both of them are not "falsey".
}

不过……

if ($the_string = a_function_call('someid123') && $another_string = another_function_call('someid123'))
{
    // $the_string is now actually a boolean true. Not sure about $another_string.
}

这是一个奇怪的错误吗?还是预期的行为?我一直认为这就像第一个场景一样,并且我一直按照这个假设进行编码。

【问题讨论】:

  • && 运算符返回真或假(布尔值)。
  • 听不懂,它们看起来一样
  • 你的意图是什么?测试a_function_call 的返回值?如果你想要返回值,用括号括起来
  • @Viney 不同的是注释,而不是代码。

标签: php


【解决方案1】:

&& 的优先级高于=。所以你的代码被解析就像你写的一样

if ($the_string = (a_function_call('someid123') && ($another_string = another_function_call('someid123'))))

这将执行以下步骤:

  1. 致电a_function_call()
  2. 如果返回真值,它会调用another_function_call() 并将结果分配给$another_string()
  3. && 表达式的真值赋给$the_string
  4. 测试if 语句中的真值。

此优先级允许您编写如下代码:

$success = function_1() && function_2();

如果= 具有更高的优先级,那将设置$success 只是来自function_1(),而不是组合。

添加括号可以解决问题:

if (($the_string = a_function_call('someid123')) 
    && ($another_string = another_function_call('someid123')))

PHP 也有 andor 运算符,类似于 &&||,但它们的优先级低于赋值;它们的存在是为了解决这个问题。你经常会在这样的代码中看到它们:

$variable = some_function(...) or die("some_function didn't work");

所以简单地将&& 替换为and 也可以解决问题。

【讨论】:

    【解决方案2】:

    关键是运算符优先级。 表达式计算如下(注意括号):

    if ($the_string = (a_function_call('someid123') && $another_string = another_function_call('someid123')))
    

    $another_stringanother_function_call() 中获取值,然后通过 AND 运算符检查 a_function_call() 返回值。

    如下添加正确的括号以获得预期的结果:

    if (($the_string = a_function_call('someid123')) && ($another_string = another_function_call('someid123')))
    

    请查看php operators precedence

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-04
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多