这里只是简单总结,这三个关键字和静态方法密切相关
this指向对象
详见静态调用不进行this绑定
- 静态调用类中所有类型的方法都不需要绑定this
- 静态方法中本身就不能有this,自然不存在绑定this
- 对象调用类中的静态方法,不需要绑定this,因为,静态方法不属于哪个对象
- 对象调用类中的非静态方法时,该方法执行之前先完成一个绑定, this绑定到调用此方法的对象
- 静态调用非静态方法是不推荐的,但在继承中常用来访问父类方法,如
parent::__construct()
class A{
public function foo(){
if (isset($this)){
echo 'this is defined~',get_class($this),"\n";
}else{
echo 'this is not defined',"\n";
}
}
}
class B{
public function bar(){ // $b->bar() $b绑定B类中的$this 并没有绑定A类中的$this
A::foo(); // 静态调用不执行this绑定 用类名调用即静态调用
}
}
$a = new A();
$a->foo(); // foo()是非静态方法,$a绑定到$this,因此 this is defined~A
A::foo(); // 静态调用 未绑定$this this is not defined
$b = new B();
$b->bar(); // bar()是非静态方法,$b绑定到$this, bar(){B::foo()-这里是静态调用,不操作$this},因此this is defined~B
B::bar(); // 静态调用 未绑定$this this is not defined
self指向本类
详见静态调用不进行this绑定
- 其实就是在类内静态访问时用
self
代替本类自己 - 这样代替的意义是,如某些原因改了类名,
self
就不用改了
class Human{
static public $head = 1;
public function show(){
// 这里self::$head等同于Human::$head 但用self更合理,如果改了类名这里就不用改了
echo self::$head,'<br>';
}
}
echo Human::$head,'<br>';
$lisi = new Human();
$lisi->show();
parent指向父类
详见静态调用不进行this绑定
- 其实就是在类内静态访问父类时用
parent
代替父类名 - 静态调用非静态方法是不推荐的,但在继承中常用来访问父类方法,如
parent::__construct()
class A{
public function foo(){
if (isset($this)){
echo 'this is defined~',get_class($this),"\n";
}else{
echo 'this is not defined',"\n";
}
}
}
class B extends A{
public function bar(){
parent::foo();
}
}
$b = new B();
$b->bar(); // bar()是非静态方法,$b绑定了bar()方法中的$this, bar(){parent::foo()-这里是静态调用,不操作$this},因此this is defined~B
B::bar(); // 静态调用 未绑定$this this is not defined
B::foo(); // 静态调用 未绑定$this this is not defined