`
dcj3sjt126com
  • 浏览: 1886243 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

yii Trying to get property of non-object错误

    博客分类:
  • YII
yii 
阅读更多

/*******************
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;
}
  • 大小: 51.5 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics