我有以下代码段:
// Some post is made and I have access to it using Input::get('name_of_field');
if (Input::has('optionalField'))
{
$thisVariable = myMagicalFunction();
}
// more operation
// being performed
ultimateFunction($thisVariable);
return true;
如您所见,有时可能未设置$thisVariable
,因此ultimateFunction($thisVariable)
有时会返回错误,指出变量未定义。我当然可以使用
if (isset($thisVariable)) ultimateFunction($thisVariable);
但有没有办法强制传递变量而不检查它是否已设置?然后我会检查它是否在ultimateFunction
内设置。
答案 0 :(得分:4)
最简单的方法是在使用变量之前声明变量: -
$thisVariable = null;
if (Input::has('optionalField'))
{
$thisVariable = myMagicalFunction();
}
// more operation
// being performed
ultimateFunction($thisVariable);
return true;
答案 1 :(得分:0)
您可以使用@
来抑制错误,因此:
ultimateFunction(@$thisVariable);
但最好先检查一下。我个人一直使用@
。这是不好的做法。
答案 2 :(得分:0)
最好是通过这种方式来抑制错误。您忽略了警告并编写了未优化的代码。即使它节省了一些时间,我强烈建议你避免这样做。
理想情况下,为$ _GET和$ _POST创建一个服务容器,为您执行此检查。如果它不存在,它可以返回null。
或者,程序性答案是这样的:
function formGet($input) {
if(isset($_GET[$input])) {
return $_GET[$input];
}
return false;
}
现在,您只需使用formGet($input)
输入数据即可。
答案 3 :(得分:-1)
可以使用PHP的错误控制操作符(at-sign):
// ...
ultimateFunction(@$thisVariable);
null
的第一个参数和内部函数将ultimateFunction
强制传递,您通常可以isset()
或empty()
查看变量是否通过。
但如果有可能,那并不意味着你应该使用它。正如@degenerate所说,它是非常糟糕的做法,因为PHP解析器使用@
运算符将上面的代码扩展为代码片段,如下所示:
$old = error_reporting(0);
ultimateFunction($thisVariable);
error_reporting($old);
此外,使用此运算符可能会降低应用程序的速度。