Can PHP Enums Have Methods?

PHP enums (both pure enums and backed enums) can have:

enum methods (static or non-static) can be marked as public, private or protected. However, since inheritance is not allowed in enumerations, private and protected are equivalent.

static Methods

It is possible to add static methods to enumerations. For example, they can serve as an alternative to constructors:

// PHP 8.1+
enum Size {
    case Small;
    case Medium;
    case Large;

    public static function fromLength(int $cm) {
        return match(true) {
            $cm < 50 => Size::Small,
            $cm < 100 => Size::Medium,
            default => Size::Large,
        };
    }
}

var_dump(Size::fromLength(75)); // enum(Size::Medium)

You may also use it for utility, for example, like so:

// PHP 8.1+
enum MyEnum: string
{
    case Foo = 'foo';
    case Bar = 'bar';
    case Baz = 'baz';

    public static function getAllValues(): array
    {
        return array_column(MyEnum::cases(), 'value');
    }
}

var_dump(MyEnum::getAllValues()); // ['foo', 'bar', 'baz']

Non-Static Methods

It is possible to add non-static methods to enumerations. They can be arbitrarily complex, or as simple as returning a static value. They are accessible on cases (as each enum case itself is a singleton object). The "$this" variable inside a non-static method refers to the case instance. For example, you can use $this with match to provide different results for different cases:

// PHP 8.1+
enum PlayingCards {
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;

    public function getColor(): string
    {
        return match($this) {
            PlayingCards::Hearts, PlayingCards::Diamonds => 'Red',
            PlayingCards::Clubs, PlayingCards::Spades => 'Black',
        };
    }
}

echo PlayingCards::Hearts->getColor(); // 'Red'
echo PlayingCards::Clubs->getColor(); // 'Black'

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.