问题
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