Introducing

PHP 8.1 - Enums


Enums are coming to PHP 8.1!

You've probably used enums one way or another in your code. Mine most often looked like this:

/**
* @method static self draft()
* @method static self published()
* @method static self archived()
  */
  class StatusEnum extends Enum {}

That's my own enum implementation I wrote a few years ago. There's of course also the very popular myclabs/php-enum, written by Matthieu Napoli.

Whichever userland enum implementation you used, you'll be happy to hear enums will be built into PHP 8.1 from now on! They look something like this:

enum Status {
    case draft;
    case published;
    case archived;
}

That's better, right? It doesn't stop there, by the way. You can also add methods to enums, which is especially useful combined with PHP 8's match operator:

enum Status {
    case draft;
    case published;
    case archived;

    public function color(): string
    {
        return match($this) {
            Status::draft = 'grey',
            Status::published = 'green',
            Status::archived = 'red',
        };
    }
}

Also, there's the possibility to assign string or integer values to enums, which makes them so-called "backed enums":

enum Status: string {
    case draft = 'draft';
    case published = 'published';
    case archived = 'archived';
}

Finally, you're probably wondering how enums are used in practice? You can type-hint them just like any other object:

class BlogPost
{
    public function __construct(public Status $status) {}
}

And you can create and pass them like so:

$post = new BlogPost(Status::draft);

Enums, they are one of those things that we've wanted for ages, and where we kind of got used to userland solutions.

This addition is a breath of fresh air, it's one of those feature where we'll look back two years from now and wonder how we ever lived without them.

Categories:
Tags:
PHP 8.1
PHP Enums
PHP