OOP PHP中變量$ a和變量$ this-> a有什麼區別?
class A{
public function example(){
$this->a = "Hello A";
$a = "Hello A";
}
}
OOP PHP中變量$ a和變量$ this-> a有什麼區別?
class A{
public function example(){
$this->a = "Hello A";
$a = "Hello A";
}
}
的代碼一個小例子來說明埃文的回答
$myA = new A();
$myA->example();
$myA->test();
class A{
private $a;
public function __construct() {
$this->a = 'Hello A';
public function example(){
$a = 'Hello A again';
echo $this->a;//print 'Hello A'
echo $a;//print 'Hello A again'
}
public function test() {
echo $this->a;//print 'Hello A'
echo $a;//E_NOTICE : type 8 -- Undefined variable: a
}
}
$this->a
代表一個類變量,並且可以從任何地方的類的範圍內進行訪問而$a
只能從函數本身內使用。
$this
是僞變量。當在對象上下文中調用方法時,此僞變量可用。 $this
是對調用對象(通常是該方法所屬的對象,但可能是另一個對象,如果該方法是從次級對象的上下文靜態調用的)的引用。
參照PHP Manual。