天天看點

yii Trying to get property of non-object錯誤

/*******************

Title:yii Trying to get property of non-object錯誤Author:insun

Blog:http://yxmhero1989.blog.163.com

****************/   

yiic 去執行時候因為調用另外一個model 是以可能會出現Trying to get property of non-object

是以在要在調用model之前判斷這個model是否存在

 這樣的代碼,就會出現上面的錯誤。

public function getCityName($id)
    {
        $model = City::model()->findByPk($id);
            return $model->name;
    }

一定要做個判斷,正确的如下:

    public function getCityName($id)
    {
        $model = City::model()->findByPk($id);
        
        if($model){
            return $model->name;
        }
        else{
            return null;
        }
    }      

譬如:

/**
  
   

    * Returns the data model based on the primary key given in the GET variable.
  
   

    * If the data model is not found, an HTTP exception will be raised.
  
   

    * @param integer the ID of the model to be loaded
  
   

    */
  
   

   public function loadModel($id)
  
   

   {
  
   

   $model=Member::model()->findByPk($id);
  
   

   if($model===null)
  
   

   throw new CHttpException(404,'抱歉,你請求的頁面不存在.');
  
   

   return $model;
  
   

   }