在这个代码片段中,我们键入$inputs['user_id']
3次。
if (isset($inputs['user_id']) && $inputs['user_id']) { // The consumer is passing a user_id
doSomethingWith($inputs['user_id']);
}
为了避免重复并避免索引user_id
不存在的任何通知,我可以做的最易读和最可靠的重构是什么?
谢谢。
在这里,重复没有任何问题。在检查变量是否已设置之前,您不能将$inputs['user_id']
分配给变量,否则将产生Notice undefined index ...
。
这里唯一可以做的是省略isset
调用并改用!empty
,如下所示:
if(!empty($inputs['user_id'])) {
doSomething($inputs['user_id']);
}
现在你只输入两次,检查
!empty($inputs['user_id'])
等于
isset($inputs['user_id']) && $inputs['user_id']
编辑:根据评论,以下是文档中的引用:
以下内容被视为空:
"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value)
所以empty(0)
或empty('0')
都会返回true
,这意味着
if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }
不会回响任何东西...或者,以礼貌的方式,我将重复上面的陈述:
!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])
编辑2:
省略isset
并替换为 !empty
仍然检查变量,索引是否已经设置,请阅读文档,其中说:
如果变量不存在,则不会生成警告。这意味着 empty() 本质上是 !isset($var) || $var == false 的简洁等价物。
这个呢:
// put validation check to the function body
function doSomethingWith($userId) {
if($userId === -1) {
// if this is not a valid user id -> return
return;
}
// do something ...
}
// initalize $user with proper default values.
// doing so you can be sure that the index exists
$user = array(
'id' => -1,
'name' => '',
...
);
// merge inputs with default values:
$user = array_merge($user, $request);
// now you can just pass the value:
doSomethingWith($user['id']);
下面可能不是每种情况的最佳方法,但绝对可以减少重复。
您的示例代码将变成:
doSomethingWith($inputs['user_id']);
你的函数看起来像这样(注意引用提供的参数,以避免未定义的变量警告):
function doSomethingWith(&$userID) {
if (empty($userID)) return;
// ... actual code here ...
}
假设0
、""
和null
无效user_ids:
if ($id = $inputs['user_id']) {
doer($id);
}
你也可以使用邪恶@
来避免在你的日志中被注意到,(我不喜欢这种方式):
if ($id = @$inputs['user_id']) {
doer($id);
}