PHP - 如何捕捉“试图获取非对象的属性”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6714591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP - How to catch a 'Trying to get property of non-object' error
提问by Jay
I am trying to catch 'Trying to get property of non-object' error with a try/catch statement but it is failing, I still get a PHP error. I am using as:
我正在尝试使用 try/catch 语句捕获“试图获取非对象的属性”错误,但它失败了,我仍然收到 PHP 错误。我正在使用:
try{
$id = Model()->find('id=1')->id;
}catch(Exception $e){
echo 'failed';
}
My find function returns an object (Active Record) and I can access the id column as shown via object prop.
我的 find 函数返回一个对象(Active Record),我可以通过 object prop 访问 id 列。
However, it will be null object if AR is not found. I thought the try statement would catch this. A work around for myself would be to use an isset(). But I am confused as to why the try statement does not accept and catch this error.
但是,如果没有找到 AR,它将是 null 对象。我认为 try 语句会捕捉到这一点。我自己的解决方法是使用 isset()。但是我很困惑为什么 try 语句不接受并捕获这个错误。
回答by deceze
try..catch
works on thrown exceptions. Errorsare not exceptions. You can silenceerrors, but please don't do that. Instead, properly check what you're getting:
try..catch
适用于抛出的异常。错误不是例外。您可以消除错误,但请不要这样做。相反,请正确检查您得到的内容:
$result = Model()->find('id=1');
if ($result) {
$id = $result->id;
} else {
// handle this situation
}
回答by F21
The model needs to be able to throw an exception.
模型需要能够抛出异常。
Here's what your model might look like:
您的模型可能如下所示:
class Model{
public function find($id){
$result = //do stuff to find by id
if (!isset($result)){
throw new Exception("No result was found for id:$id");
}
return $result
}
}
Then you would use your try/catch block:
然后你会使用你的 try/catch 块:
try{
$id = Model()->find('id=1')->id;
}catch(Exception $e){
echo 'failed';
}
However, exceptions should only be thrown under "exceptional" circumstances. I don't think using exceptions to direct program flow is the right way to go about it.
但是,异常应该只在“异常”情况下抛出。我不认为使用异常来指导程序流是正确的方法。
Having said that, if returning a NULL when you attempt to retrieve the ID property is an exceptional situation, then exceptions are certainly suitable.
话虽如此,如果在您尝试检索 ID 属性时返回 NULL 是一种例外情况,那么例外当然是合适的。