当if子句具有未定义的变量时应该发生什么

时间:2013-05-14 00:26:28

标签: php

我正在使用遗留代码库,请看:

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块,如果没有定义子句中的某个变量?

2 个答案:

答案 0 :(得分:2)

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

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

P.S。 undefined变量转换为NULL,算术运算符中的NULL转换为0。