0
從另一種方法中調用同一類中的方法時,最好是使用$this
還是避免它,還是根本沒有區別?
我可以看到使用$this
的一個好處是它是明確的。例如:
class A {
public function a() {
$x = $this->b();// or $x = b()
}
public function b() {
//
}
}
從另一種方法中調用同一類中的方法時,最好是使用$this
還是避免它,還是根本沒有區別?
我可以看到使用$this
的一個好處是它是明確的。例如:
class A {
public function a() {
$x = $this->b();// or $x = b()
}
public function b() {
//
}
}
與其它語言不同,像C++
和C#
和Java
,訪問PHP
一類的成員屬性,必須始終使用$this
爲對財產預選賽。
例如:
class Test {
public $myVariable;
public function __construct($a) {
$this->myVariable = $a;
// $myVariable doesn't exist, must always use $this-><*>
}
}
試過'$ X = B()',它根本不工作。 –
你有兩種方法。 'self :: methodName()'和'$ this-> methodName()'。 –
正如@GrasDouble所說的,如果沒有'$ this',它就無法工作。如果你真的執行你的代碼而沒有'$ this',你將會收到: '致命錯誤:調用未定義函數b()在/yourpath/yourfile.php在第n行 –