2017-11-11 39 views
1

這是我的課程。 getPosts方法返回一個數組,但我無法在proceedPosts中獲得對它的訪問。當我試圖在瀏覽器中打印時,它向我顯示一個錯誤,$result變量不是defined不明白爲什麼我不能通過另一個課程方法獲得結果

class myClass 
    { 
     public $myposts; 

     public function getPosts() 
     { 
      $result = $this->myposts = array('a','b','c'); 

      return $result; 

     } 

     public function handlePosts() 
     { 
      echo $result; 
     } 
    } 

    $myObj = new myClass(); 
    $myObj->getPosts(); 
    $myObj-> handlePosts(); 

有人能解釋我爲什麼嗎?謝謝。

回答

0

第一個問題是$result;handlePosts()功能稱爲第二個你想回應一個數組,你必須有toString所以讓你的代碼工作試試這個:

<?php 

    class myClass 
     { 
      public $myposts; 

      public function getPosts() 
      { 
       $result = $this->myposts = array('a','b','c'); 

       return $result; 

      } 

      public function handlePosts() 
      { 
       var_dump($this->getPosts()); 
      } 
     } 

     $myObj = new myClass(); 

     $myObj-> handlePosts(); 

    ?> 
+0

非常感謝你兄弟。它爲我工作。 –

0

$result變量在getPosts()創建方法,並且只存在於此方法中(如果您願意,也可以存在)。

你在此方法得到的回報將只取得了意義,如果你下面有代碼:

$result_from_get_post_method = $myObj->getPosts(); 

如果你想使類範圍訪問的變量,你將不得不在前面使用$this你的變量名稱,如:

class myClass 
{ 
    public $myposts; 

    public $result; 

    public function getPosts() 
    { 
     $this->result = $this->myposts = array('a','b','c'); 

     return $this->result; 

    } 

    public function handlePosts() 
    { 
     echo $this->result; 
    } 
} 

$myObj = new myClass(); 
$result_of_method = $myObj->getPosts(); 
print($result_of_method); // prints result_of_method which contains array 
print($myObj->result); // does the same as line above, by calling object variable 
$myObj->handlePosts(); // echos the array 
相關問題