How to make this PHP snippet work without warning?

天涯浪子 提交于 2019-12-25 07:08:51

问题


The code is short,but complete:

function process($obj)
{
    if(empty($obj))return 1;
    return 2;
}


echo process($arr['nosuchkey']);

As we all know, calling empty($arr['nosuchkey']) will never report warnings.

But process($arr['nosuchkey']) will report a notice.

Is there a workaround without disabling warnings; say, by syntax?


回答1:


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']);

Or passing the key separately

echo process($arr, 'nosuchkey');

Be sure you know the difference between empty(), isset() and array_key_exists() - they catch a lot of people out.




回答2:


Try this one

 function process(&$obj)

Im not sure if it will work




回答3:


Maybe

function process($obj, $index = null) {
    if(is_array($obj))
    {
         if(!array_key_exists($index, $obj))
             return 1;
         else
             return 2;
    }

    if(empty($obj)) 
        return 1;

    return 2;

}

Please don't hide warnings with @ whenever possible.



来源:https://stackoverflow.com/questions/1454575/how-to-make-this-php-snippet-work-without-warning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!