/

PHP 中 this self parent 用法

  • self:: 调用本类属性、方法;可以抑制方法多态性。
  • parent:: 调用父类属性、方法。
  • static:: 调用静态属性、方法;可以体现多态性。
  • $this-> 调用本实例的属性、方法;$this:: 可以调用静态属性、方法;但是无法在静态方法里使用;可以体现多态性。
  • -> object-operator, you always know you’re dealing with an instance.
  • :: scope-resolution-operator, you need more information about the context.
<?php
class A
{
public static function newStaticClass()
{
return new static();
}

public static function newSelfClass()
{
return new self();
}

public function newThisClass()
{
return new $this();
}
}

class B extends A
{
public function newParentClass()
{
return new parent();
}
}

class C extends B
{
public static function newSelfClass()
{
return new self();
}
}

$c = new C();

var_dump($c::newStaticClass()); // C and is same C::newStaticClass()
var_dump($c::newSelfClass()); // C because self now points to "C" class
var_dump($c->newThisClass()); // C
var_dump($c->newParentClass()); // A because parent was defined *way back* in class "B"

References