0

我正在使用旧代码库,请参阅:

public static function blah($formData = array()) {
  $x = null;
  $y = null;

  if ($formData['x'] || $formData['y']) {
    $x = $formData['x'];

    if ($formData['y'])
      $y = $formData['y'];

    return $x - $y;
  }

  //does some other stuff with x/y and then returns the result 
}

显然,这段代码糟糕到无法忍受,但我不完全确定预期的效果应该是什么。我发现这个问题的原因是因为我在启用严格检查的环境中运行代码,并且该if子句导致函数死亡,因为在调用该函数的至少某些实例中既没有也没有定义xy

如果没有严格检查,如果不定义子句中的变量之一,是否会跳过 if 块?

4

2 回答 2

2

根据http://php.net/manual/en/types.comparisons.php, undefined 被视为FALSE用于if测试目的(尽管他们显然建议不要使用它)。

于 2013-05-14T00:31:20.223 回答
0
case defined `$formData['x']` only -- function return `$formData['x']`
case defined `$formData['y']` only -- function return `-$formData['y']`
case defined `$formData['x']` and `$formData['y']` -- function return `$formData['x']-$formData['y']`
case all undefined -- your function will continue

PS 未定义的变量转换为 NULL,算术运算符中的 NULL 转换为 0。

于 2013-05-14T00:51:15.213 回答