我正在使用遗留代码库,请看:
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块,如果没有定义子句中的某个变量?
答案 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。