PHP - How to catch a 'Trying to get property of non-object' error

前端 未结 2 1353
被撕碎了的回忆
被撕碎了的回忆 2020-12-10 10:41

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         


        
相关标签:
2条回答
  • 2020-12-10 11:19

    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
    }
    
    0 讨论(0)
  • 2020-12-10 11:22

    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{  
    
        $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.

    0 讨论(0)
提交回复
热议问题