2016-02-27 15 views
0

從另一種方法中調用同一類中的方法時,最好是使用$this還是避免它,還是根本沒有區別?

我可以看到使用$this的一個好處是它是明確的。例如:

class A { 
    public function a() { 
    $x = $this->b();// or $x = b() 
    } 

    public function b() { 
    // 
    } 
} 
+2

試過'$ X = B()',它根本不工作。 –

+0

你有兩種方法。 'self :: methodName()'和'$ this-> methodName()'。 –

+0

正如@GrasDouble所說的,如果沒有'$ this',它就無法工作。如果你真的執行你的代碼而沒有'$ this',你將會收到: '致命錯誤:調用未定義函數b()在/yourpath/yourfile.php在第n行 –

回答

1

與其它語言不同,像C++C#Java,訪問PHP一類的成員屬性,必須始終使用$this爲對財產預選賽。

例如:

class Test { 
    public $myVariable; 

    public function __construct($a) { 
     $this->myVariable = $a; 
     // $myVariable doesn't exist, must always use $this-><*> 
    } 
} 
相關問題