2010-03-02 49 views
5

我想弄清楚如何在自己的類中使用方法。例如:PHP:我如何在自己的類中訪問/使用方法?

class demoClass 
{ 
    function demoFunction1() 
    { 
     //function code here 
    } 

    function demoFunction2() 
    { 
     //call previously declared method 
     demoFunction1(); 
    } 
} 

,我發現是工作的唯一方法是,當我創建的方法中的類的新intsnace,然後調用它。例如:

class demoClass 
{ 
    function demoFunction1() 
    { 
     //function code here 
    } 

    function demoFunction2() 
    { 
     $thisClassInstance = new demoClass(); 
     //call previously declared method 
     $thisClassInstance->demoFunction1(); 
    } 
} 

但這不覺得正確......或者是這樣嗎? 有幫助嗎?

感謝

回答

10

$this->的對象的內部,或者在self::靜態上下文(用於或者從一個靜態方法)。

7

您需要使用$this來指代當前對象:

僞變量$this時可用的方法是從對象內部調用。 $this是對調用對象(通常是該方法所屬的對象,但可能是另一個對象,如果該方法是從次級對象的上下文靜態調用的)的引用。

所以:

class demoClass 
{ 
    function demoFunction1() 
    { 
     //function code here 
    } 

    function demoFunction2() 
    { 
     // $this refers to the current object of this class 
     $this->demoFunction1(); 
    } 
} 
4

用 「$這個」 來稱呼自己。

class demoClass 
{ 
    function demoFunction1() 
    { 
     //function code here 
    } 

    function demoFunction2() 
    { 
     //call previously declared method 
     $this->demoFunction1(); 
    } 
} 
5

只需使用:

$this->demoFunction1(); 
5

使用$this關鍵字來引用當前類的實例:

class demoClass 
{ 
    function demoFunction1() 
    { 
     //function code here 
    } 

    function demoFunction2() 
    { 
     $this->demoFunction1(); 
    } 
} 
相關問題