2010-11-08 182 views
10

可能重複:
PHP: self vs this

你好, 你能幫我理解PHP變量名$this的意思嗎?

謝謝你的幫助。

+2

可能重複:http://stackoverflow.com/questions/151969/php-self-vs-this。另外,請不要在提問中太可愛。 ;) – birryree 2010-11-08 15:00:18

+2

祝賀您在12歲時擴大知識!但由於這與問題無關,您可以編輯該問題以將其刪除嗎? – 2010-11-08 15:02:07

+0

似乎堆棧溢出的人不知道'我12歲,這是什麼'是指。 – JAL 2010-11-08 15:06:25

回答

16

$this是指你在課堂上。

例如

Class Car { 

    function test() { 
     return "Test function called"; 
    } 

    function another_test() { 
     echo $this->test(); // This will echo "Test function called"; 
    } 
} 

希望這有助於。

+0

這是一種引用自身的方法...或調用方法或從本身讀取變量。 – jodm 2010-11-08 15:02:47

+5

實際上,self指您當前所在的類。$ this指的是您所在類的當前對象實例。 – 2010-11-08 15:02:49

+0

它不會'echo「測試函數稱爲」',因爲您正在訪問'test'成員變量(不存在),而不是方法'test()'。你需要將它改爲'echo $ this-> test()'... – ircmaxell 2010-11-08 15:03:01

1

$this是在對象中使用的受保護變量,$this允許您在內部訪問類文件。

Class Xela 
{ 
    var age; //Point 1 

    public function __construct($age) 
    { 
     $this->setAge($age); //setAge is called by $this internally so the private method will be run 
    } 

    private function setAge($age) 
    { 
     $this->age = $age; //$this->age is the variable set at point 1 
    } 
} 

它基本上是一個變量範圍的問題,$this只允許已啓動,是指對象,只有其父母,你可以運行私有方法和設置私有變量,其中一個對象中因爲你無法做到這一點。

self關鍵字是非常相似的除了它指的是靜態方法類中,靜態基本上意味着你不能使用$this作爲它不是一個對象是,你必須使用self::setAge();,如果該setAge方法聲明爲static那麼你不能從該對象的瞬間/叫它object

一些鏈接供你上手:

+0

雖然我知道你正在向OOP新人解釋,但請不要將對象稱爲類。 $ this用於引用對象屬性和方法,而self ::用於引用類屬性和方法。 我認爲重要的是要解釋兩者之間的差異。 – Craige 2010-11-08 15:24:48