【问题标题】:Nested negative if statements with assignments in condition带有条件赋值的嵌套否定 if 语句
【发布时间】:2017-05-28 06:19:01
【问题描述】:

我有以下代码:

if (!$x = some_function(1)) {
    if (!$x = some_function(2)) {
        return something;
    }
}

我想知道以下哪些语句是等价的:

A.

if (some_function(1)) {
    $x = some_function(1));
}
else if (some_function(2)) {
    $x = some_function(2));
}
else {
    return something;
}

或者如果它本质上是说它应该被覆盖,就像这样:

乙。

if (some_function(1)) {
    $x = some_function(1));
}
if (some_function(2)) {
    $x = some_function(2));
}
if (!$x) {
    return something;
}

问题的另一种表述方式:在if 语句中的赋值中,是先为false 评估变量,然后再为false 赋值,还是先赋值,然后评估变量下一个?

【问题讨论】:

  • 先赋值给$x,然后是条件测试。
  • 另外,这个赋值仍然在作用域内,所以很容易在这个地方不经意间泄露变量。

标签: php if-statement conditional-statements variable-assignment


【解决方案1】:

第一个语句不等同于其他任何语句。相当于这样:

$x = some_function(1); // assign $x first
if(!$x){ // check if $x is falsy
  $x = some_function(2); // overwrite $x (not the function itself)
  if(!$x){ // check if $x is still falsy
   // do stuff
  }
}

或者,如果变量不重要,这也是等价的

if(!some_function(1) && !some_function(2)){...}

唯一的区别是第一个总是为$x 提供一个值,这可能在其他地方使用。

这个也一样,用三进制

$x = some_function(1) ? some_function(1) : some_function(2);
if(!$x) // do stuff

【讨论】:

    【解决方案2】:

    感谢 Scuzzy 的澄清 - 似乎正确的等价物是这样的:

    if (some_function(1)) {
        $x = some_function(1));
    }
    if (!$x && some_function(2)) {
        $x = some_function(2));
    }
    if (!$x) {
        return something;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 2020-09-13
      相关资源
      最近更新 更多