PHP-如何捕获“试图获取非对象的属性"错误 [英] PHP - How to catch a 'Trying to get property of non-object' error
问题描述
我正在尝试通过try/catch语句捕获试图获取非对象的属性"错误,但失败了,但仍然出现PHP错误.我正在使用:
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{
$id = Model()->find('id=1')->id;
}catch(Exception $e){
echo 'failed';
}
我的find函数返回一个对象(活动记录),我可以通过对象prop来访问id列.
My find function returns an object (Active Record) and I can access the id column as shown via object prop.
但是,如果未找到AR,它将为空对象.我认为try语句会抓住这一点.我自己的解决方法是使用isset().但是我对为什么try语句不接受并捕获此错误感到困惑.
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.
推荐答案
try..catch
适用于抛出的异常. 错误也不例外.您可以静音错误,但请不要这样做.相反,请正确检查您得到的内容:
try..catch
works on thrown exceptions. Errors are not exceptions. You can silence errors, but please don't do that. Instead, properly check what you're getting:
$result = Model()->find('id=1');
if ($result) {
$id = $result->id;
} else {
// handle this situation
}
这篇关于PHP-如何捕获“试图获取非对象的属性"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!