class Base {
public function __construct() {
echo "Base contructor!", PHP_EOL;
}
}
class Child {
public function __construct() {
parent::__construct();
echo "Child contructor!", PHP_EOL;
}
}
new Child;
// 输出:
// Base contructor!
// Child contructor!
class Base {
public function __construct() {
echo "Base constructor!", PHP_EOL;
}
public static function getSelf() {
return new self();
}
public static function getInstance() {
return new static();
}
public function selfFoo() {
return self::foo();
}
public function staticFoo() {
return static::foo();
}
public function thisFoo() {
return $this->foo();
}
public function foo() {
echo "Base Foo!", PHP_EOL;
}
}
class Child extends Base {
public function __construct() {
echo "Child constructor!", PHP_EOL;
}
public function foo() {
echo "Child Foo!", PHP_EOL;
}
}
$base = Child::getSelf();
$child = Child::getInstance();
$child->selfFoo();
$child->staticFoo();
$child->thisFoo();
程序输出结果如下:
Base constructor!
Child constructor!
Base Foo!
Child Foo!
Child Foo!
在函数引用上,self与static的区别是:对于静态成员函数,self指向代码当前类,static指向调用类;对于非静态成员函数,self抑制多态,指向当前类的成员函数,static等同于this,动态指向调用类的函数。
parent、self、static三个关键字联合在一起看挺有意思,分别指向父类、当前类、子类,有点“过去、现在、未来”的味道。 this
self与this是被讨论最多,也是最容易引起误用的组合。两者的主要区别如下: