Trait

枚举也能使用 trait,行为和 class 一样。 留意在枚举中 use trait 不允许包含属性。 只能包含方法、静态方法。 包含属性的 trait 会导致 fatal 错误。

<?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

User Contributed Notes

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