在OOP PHP中变量$ a和变量$ this-> a之间有什么不同?
class A{
public function example(){
$this->a = "Hello A";
$a = "Hello A";
}
}
答案 0 :(得分:3)
$this->a
表示一个类变量,可以从类的范围内的任何地方访问,而$a
只能在函数本身内使用。
答案 1 :(得分:2)
$this
是伪变量。从对象上下文中调用方法时,此伪变量可用。 $this
是对调用对象的引用(通常是方法所属的对象,但如果从辅助对象的上下文中静态调用该方法,则可能是另一个对象)。
参考 PHP Manual 。
答案 2 :(得分:1)
用于说明Evan的答案的代码示例
$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
}
}