我正在使用一个遗留代码库,看到如下:
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
子句导致函数死亡,因为x
和y
都没有在至少一些被调用的函数实例中定义。
如果没有严格的检查,如果子句中的一个变量没有定义,是否跳过if块?
根据http://php.net/manual/en/types.comparisons.php,在if
测试中,undefined被视为FALSE
(尽管他们显然不建议这样做)。
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
注:未定义变量强制转换为NULL,算术运算符中的NULL强制转换为0。