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。