PHP 的 后期静态绑定

等级 4197 次按键

使用 new static() 和 static::class,使从 Base 继承的方法引用实际调用的类(Child);输出“Child”。

PHP 代码

1class Base {
// 返回类型 static:调用该方法的那个类的实例
2 public static function create(): static {
// new static() 创建被调用的类,而 new self() 总是创建 Base
3 return new static();
4 }
5
6 public function name(): string {
// static::class 是对象的实际类名,这里是 Child
7 return static::class;
8 }
9}
10
// Child 没有新增内容,继承 create() 和 name()
11class Child extends Base {}
12
// create() 返回 Child,所以输出“Child”
13echo Child::create()->name();

运行结果

Child
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • :× 6
  • (× 5
  • )× 5
  • {× 4
  • }× 4
  • ;× 3
  • -× 1
  • >× 1

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习