枚举静态方法

枚举也能有静态方法。 在枚举中静态方法主要用于取代构造器,如:

<?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 效果是相同的。

add a note

User Contributed Notes 2 notes

up
33
niloofarfs
11 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');
    }
}

?>
up
0
Aaron Saray
2 months ago
Need to retrieve all the names and values immediately from a backed enum (for something like a select box) and you don't want to loop over `Enum::cases()`?  Try this:

<?php
enum Suit
: string
{
    case
Hearts = 'H';
    case
Diamonds = 'D';
    case
Clubs = 'C';
    case
Spades = 'S';

    public static function
forSelect(): array
    {
      return
array_combine(
       
array_column(self::cases(), 'value'),
       
array_column(self::cases(), 'name')
      );
    }
}

Suit::forSelect();
?>

Put `forSelect()` in a trait and use it in any enum you have that needs this functionality.
To Top