2010-07-21 74 views
-1

我有下面的代碼:問題與PHP OOP

class the_class { 
    private the_field; 

    function the_class() { 
    the_field = new other_class(); //has other_method() 
    } 

    function method() { 
    $this->the_field->other_method(); //This doesn't seem to work 
    } 
} 

這有什麼錯在這裏的語法?方法調用似乎總是返回true,就好像方法調用有問題一樣。 或者是方法調用所有權利,我應該調試other_method()本身?

TIA,彼得

+0

非常感謝你。完成了! 我是盲人,呃? ;-)對不起。 – 2010-07-21 11:42:39

+0

你仍然可能想接受已花時間回覆的人的回答。 – 2010-07-21 16:02:31

回答

3

你已經錯過了PHP變量符號和階級屬性的訪問:

  • $符號是必須爲每個PHP 變量(不是常數)。
  • $this關鍵字/自變量是必須訪問當前類或父類成員。在某些情況下,您可能必須特別針對靜態成員使用「自我」或「父母」關鍵字。

    class the_class { 
        private $the_field;//changes 
    
        function the_class() { 
        $this->the_field = new other_class(); //has other_method()//changes 
        } 
    
        function method() { 
        $this->the_field->other_method(); //This doesn't seem to work 
        } 
    } 
    
2

你需要使用在構造函數中$this->the_field了。

6

您需要爲變量使用美元符號。所以,你的代碼將因此成爲:

class the_class { 
    private $the_field; 

    function the_class() { 
    $this->the_field = new other_class(); 
    // assigning to $this->... assigns to class property 
    } 

    function method() { 
    $this->the_field->other_method(); 
    } 
}