PHP の 交差型

レベル 5502 打鍵

複数のインターフェースを要求するために交差型を使用します。

PHP のコード

// 1つ目のインターフェース
1interface Printable {
2 public function print(): string;
3}
4
// 2つ目のインターフェース
5interface JsonExportable {
6 public function serialize(): string;
7}
8
// クラスは複数のインターフェースを実装できる
9class Document implements Printable, JsonExportable {
// プロモーションでprivateな$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 タイピング練習のトップへ