当从另一个方法中调用同一类中的方法时,是使用 $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-><*>
}
}