带有赋值条件的嵌套否定if语句

时间:2017-01-12 23:46:43

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

我有以下代码:

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

我想知道以下哪些陈述是等价的:

一个。

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,或者首先进行赋值,然后评估下一个变量?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

感谢Scuzzy澄清 - 似乎正确的等同于:

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