如何让这个 PHP 代码片段在没有警告的情况下工作? [英] How to make this PHP snippet work without warning?
本文介绍了如何让这个 PHP 代码片段在没有警告的情况下工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码很短,但完整:
function process($obj)
{
if(empty($obj))return 1;
return 2;
}
echo process($arr['nosuchkey']);
众所周知,调用 empty($arr['nosuchkey'])
永远不会报告警告.
As we all know, calling empty($arr['nosuchkey'])
will never report warnings.
但是process($arr['nosuchkey'])
会报告一个通知.
是否有不禁用警告的解决方法;比如说,通过语法?
Is there a workaround without disabling warnings; say, by syntax?
推荐答案
您可以使用 错误控制运算符@ 但这将抑制的不仅仅是通知.
You can use the error control operator @ but that will suppress a lot more than just notices.
echo @process($arr['nosuchkey']);
你最好在函数调用前检查:
You would be better off checking before the function call:
if (array_key_exists('nosuchkey', $arr))
echo process($arr['nosuchkey']);
或者单独传递密钥
echo process($arr, 'nosuchkey');
确保您知道empty()
、isset()
和 array_key_exists()
- 他们把很多人赶出去了.
Be sure you know the difference between empty()
, isset()
and array_key_exists()
- they catch a lot of people out.
这篇关于如何让这个 PHP 代码片段在没有警告的情况下工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文