トレイト

列挙型ではトレイトを使えます。 列挙型におけるトレイトは、クラスにおけるそれと同じ振る舞いをします。 注意すべきことは、列挙型で use されるトレイトには、プロパティが含まれていてはいけないという点です。 use されるトレイトには、 メソッドと static メソッドだけを含めることができます。 プロパティを持つトレイトの場合、致命的なエラーが発生します。

<?php

interface Colorful
{
public function
color(): string;
}

trait
Rectangle
{
public function
shape(): string {
return
"Rectangle";
}
}

enum
Suit implements Colorful
{
use
Rectangle;

case
Hearts;
case
Diamonds;
case
Clubs;
case
Spades;

public function
color(): string
{
return match(
$this) {
Suit::Hearts, Suit::Diamonds => 'Red',
Suit::Clubs, Suit::Spades => 'Black',
};
}
}
?>
add a note add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top