2013-06-25 24 views
-2

我遇到了「調用非對象成員函數」的問題 - 錯誤。 字段$ other_class不適用於將來的操作。 如何填寫和使用對象$ other_class?謝謝。對象在自己的類中不可見PHP 5 OOP

$myclass = new MyClass; 

    $other_class = $myclass -> GetOther_Class(); 
    var_dump($other_class); //Works! 

    echo $other_class; //Call to a member function on a non-object - Error 

    class MyClass 
    { 
    private $other_class; 

     function __construct() 
     { 
      $other_class = new Other_Class; //Fill $other_class 
      //I tried also 
      //$this -> other_class = new Other_Class; 
     } 

     public function GetOther_Class() 
     { 
      return $other_class;  
     } 

     private function Generate() 
     { 
      $other_class -> SetTitle ("Hello"); 
     } 

     public function __toString() 
     { 
     $this->Generate(); 
     } 


    } 
+0

總是使用'$ this->'來訪問類成員(除非它們是靜態的)。 – x4rf41

+0

錯誤不在你說的行中。當你修好後你會得到下一個。所以要小心:爲了正確理解錯誤,您需要找到實際產生的代碼行。 – hakre

回答

1

的問題是你引用$other_class等都將始終爲空或未定義當您嘗試在GET方法返回。 當引用當前類的屬性,你需要$this->前綴是:

class MyClass 
{ 
    private $other_class; 

    function __construct() 
    { 
     $this->other_class = new Other_Class; //Fill $other_class 
     //I tried also 
     //$this -> other_class = new Other_Class; 
    } 

    public function GetOther_Class() 
    { 
     return $this->other_class;  
    } 

    private function Generate() 
    { 
     $this->other_class -> SetTitle ("Hello"); 
    } 

    public function __toString() 
    { 
     $this->Generate(); 
    } 
} 
+0

非常感謝。我實際上是一個C#編碼器,這很煩人。 MrCode的Cookies和所有其他好人。 – bergman

+0

嗯,是的,C#允許你引用沒有前綴的屬性,所以我可以理解你編碼PHP時的困惑:) – MrCode

0

你的錯誤是因爲這下面的方法失敗。當你使用echo時,它會調用__toString()方法。

private function Generate() 
    { 
     $other_class -> SetTitle ("Hello"); 
    } 

嘗試在這部分改變這

private function Generate() 
    { 
     $this->other_class -> SetTitle ("Hello"); 
    } 

,並在構造函數中

function __construct() 
    { 
     $this -> other_class = new Other_Class; 
    } 

    public function GetOther_Class() 
    { 
     return $this->other_class;  
    } 
0
public function GetOther_Class() 
    { 
     return $other_class;  
    } 

返回它不存在,你應該返回$this->other_class而不是本地$other_class ;