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',
};
}
}
?>
添加备注

用户贡献的备注 1 note

up
17
wervin at mail dot com
1 year ago
One good example of a trait, would be to give a lot of enums a method to retrieve their cases, values or both.<?phptrait EnumToArray{    public static function names(): array    {        return array_column(self::cases(), 'name');            }    public static function values(): array    {        return array_column(self::cases(), 'value');    }    public static function asArray(): array    {        if (empty(self::values())) {            return self::names();        }                if (empty(self::names())) {            return self::values();        }                return array_column(self::cases(), 'value', 'name');    }}?>Some example outputs:<?phpvar_export(IpVersion::names());     // ['Ipv4', 'IPv6']var_export(IpVersion::values());    // []var_export(IpVersion::asArray());   // ['IPv4', 'IPv6']var_export(Language::names());      // ['en', 'es']var_export(Language::values());     // ['English', 'Spanish']var_export(Language::asArray());    // ['en' => 'English', 'es' => 'Spanish']
To Top