2013-05-15 15 views
-1

我對Yii相當陌生,在嘗試製作我自己的博客應用程序時,我使用此函數爲我的帖子添加了評論。Yii,致命錯誤:在非對象上調用成員函數addComment()

不過,我已經根據理論做的一切,但我仍然得到一個:

Fatal error: Call to a member function addComment() on a non-object in /htdocs/blog/protected/controllers/PostController.php on line 63 

我post.php中的模型類具有這樣的功能:

public function addComment($comment){ 
     $comment->tbl_post_id = $this->id; 
     return $comment->save(); 
    } 

而且我PostController.php有這些兩個函數,一個用於創建註釋,另一個用於修改視圖文件。

public function actionView($id) 
    { 
     $post=$this->loadModel($id); 
     $comment=$this->createComment($post); 
     $this->render('view',array(
     'model'=>$post, 
      'comment'=>$comment, 
)); } 

    protected function createComment($post) 
    { 
    $comment=new Comment; 
    if(isset($_POST['Comment'])) 
    { 
     $comment->attributes=$_POST['Comment']; 
     if($post->addComment($comment)) // **This is line 63** 
     { 
     Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added."); 
     $this->refresh(); 
     } 
} 
    return $comment; 
    } 

所以邏輯上,我呼籲使用後$> addComment Post模型類中的成員函數addComment,和模型的所有成員函數初始化吧?邏輯學家不應該這樣正確嗎?但是,我收到上述致命錯誤。

我在做什麼錯?

任何幫助,將不勝感激。

問候,

P.S - 我很抱歉,如果我做一些非常愚蠢的。

回答

2

$post是不是一個對象,因爲你沒有聲明它在線63隨地

protected function createComment($issue) 
{ 
    $comment=new Comment; 
    if(isset($_POST['Comment'])) 
    { 
    $comment->attributes=$_POST['Comment']; 
    if($post->addComment($comment)) // **This is line 63** 
    { 
     Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added."); 
     $this->refresh(); 
    } 
    } 
    return $comment; 
} 

他尋找一個名爲$post變量不存在。你必須創建或從數據庫負載就像你正在做的到你actionView()

$post=$this->loadModel($id); 

顯然,對於加載它,你需要$id必須被傳遞給你的createComment()功能

+0

那好吧!知道了,謝謝你..我知道這確實是一個愚蠢的錯誤。 –

+0

但是我有一個小小的疑問,那就是爲什麼$ comment變量正常工作,因爲它是對Comment的模型類的引用。我已經在課程的任何地方初始化了它? –

+0

'$ comment = new Comment;'你已經在'createComment()'方法的第一行初始化它 – DonCallisto

0

你有addComment ()方法模型類。所以,你可以通過對象Post來處理這個方法。

你的宣言

$post->addComment($comment) 

是正確的,但沒有$發佈對象。所以,只要創建日誌模型的實例作爲

$post=new Post(); 

最後你的代碼應該像

if(isset($_POST['Comment'])) 
{ 
    $comment->attributes=$_POST['Comment']; 
    $post=new Post(); 

    if($post->addComment($comment)) // **This is line 63** 
    { 
     Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added."); 
     $this->refresh(); 
    } 
} 
相關問題