Additional use-case examples:
<?php
trait EnumNamesTrait
{
abstract public static function cases(): array;
public static function names(): array
{
return array_map(fn($enum) => $enum->name, static::cases());
}
}
trait EnumValuesTrait
{
abstract public static function cases(): array;
public static function values(): array
{
return array_map(fn($enum) => $enum->value, static::cases());
}
}
trait EnumArraySerializableTrait
{
use EnumNamesTrait;
use EnumValuesTrait;
public static function array(): array
{
return array_combine(static::names(), static::values());
}
}
trait EnumJsonSerializableTrait
{
use EnumArraySerializableTrait;
public static function jsonSerialize(): string
{
return json_encode(static::array());
}
}
enum Suit: string
{
case Clubs = '♣';
case Diamonds = '♦';
case Hearts = '♥';
case Spades = '♠';
use EnumJsonSerializableTrait;
public const DEFAULT = self::Hearts;
public static function default(): static
{
return self::DEFAULT;
}
}
var_dump(
Suit::cases(),
Suit::values(),
Suit::names(),
Suit::array(),
Suit::jsonSerialize(),
Suit::default(),
);