Enumeration static methods

Enumerations may also have static methods. The use for static methods on the enumeration itself is primarily for alternative constructors. E.g.:

<?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,
        };
    }
}
?>

Static methods may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed.

add a note add a note

User Contributed Notes 1 note

up
9
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');
    }
}

?>
To Top