PHP 的 交集类型

等级 5502 次按键

使用交集类型要求多个接口。

PHP 代码

// 第一个接口
1interface Printable {
2 public function print(): string;
3}
4
// 第二个接口
5interface JsonExportable {
6 public function serialize(): string;
7}
8
// 一个类可以实现多个接口
9class Document implements Printable, JsonExportable {
// 通过属性提升定义私有属性$content
10 public function __construct(private string $content) {}
11
// Printable要求的方法
12 public function print(): string {
13 return $this->content;
14 }
15
// JsonExportable要求的方法,返回JSON
16 public function serialize(): string {
17 return json_encode(["content" => $this->content]);
18 }
19}
20
// 交集类型(PHP 8.1+):参数必须同时实现两个接口
21function process(Printable&JsonExportable $item): void {
22 echo $item->print();
23}
24
// Document同时满足两者,因此输出Hello
25process(new Document("Hello"));

运行结果

Hello
用这段代码练习打字

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

这段代码中的符号

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

  • (× 10
  • )× 10
  • {× 7
  • }× 7
  • ;× 6
  • :× 5
  • $× 5
  • "× 4
  • >× 4
  • _× 3

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习