前言与parent、static以及this的区别
parent
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!
有了static的静态延迟绑定功能,可以在运行时动态确定归属的类。例如:
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();
Child constructor!
Base Foo!
Child Foo!
Child Foo!
parent、self、static三个关键字联合在一起看挺有意思,分别指向父类、当前类、子类,有点“过去、现在、未来”的味道。槽点
$class = static::class;
return $this instanceof $class;
// 或者这样:
return $this instanceof static;When to use self over $this?总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对自学php网的支持。