Skip to content

PHP 8.1 enum with methods and match expression

PHP Dasun Kalupahana 75 views

<?php

enum Status: string
{
    case Draft = 'draft';
    case Published = 'published';
    case Archived = 'archived';

    public function label(): string
    {
        return match ($this) {
            self::Draft => 'Work in progress',
            self::Published => 'Live',
            self::Archived => 'Hidden',
        };
    }

    public static function fromLabelSafe(string $v): self
    {
        return self::tryFrom($v) ?? self::Draft;
    }
}

echo Status::from('published')->label(), PHP_EOL;                 // Live
echo Status::fromLabelSafe('nope')->name, PHP_EOL;                // Draft
echo implode(', ', array_column(Status::cases(), 'value')), PHP_EOL; // draft, published, archived

Backed enums can hold methods and static helpers. match gives a strict value mapping, and tryFrom with ?? provides a safe fallback. Needs PHP 8.1+.

Learn more on the blog

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.