枚举静态方法
枚举也能有静态方法。 在枚举中静态方法主要用于取代构造器,如:
<?php
enum Size
{
case Small;
case Medium;
case Large;
public static function fromLength(int $cm): static
{
return match(true) {
$cm < 50 => static::Small,
$cm < 100 => static::Medium,
default => static::Large,
};
}
}
?>
仅管 enum 可以包括 public、private、protected 的静态方法, 但由于它不支持继承,因此在实践中 private 和 protected 效果是相同的。

User Contributed Notes 1 note
niloofarfs ¶
3 months ago
To get all scalar equivalents values of Backed Enum as an array you could define a method in your Enum:
<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
public static function values(): array
{
return array_column(self::cases(), 'value');
}
}
?>
备份地址:http://www.lvesu.com/blog/php/language.enumerations.static-methods.php