1 min read

PHP Enumerations (Enums)

Enumerations, or Enums, allow a developer to define a custom type that is limited to a discrete set of possible values. They are useful when you have a variable that can only take one of a small set of possible values.

Enums were introduced in PHP 8.1.

Basic Enums

A basic enum is a type that has a fixed number of possible values.

<?php
enum Status {
    case DRAFT;
    case PUBLISHED;
    case ARCHIVED;
}

function setStatus(Status $status) {
    // ...
}

setStatus(Status::DRAFT);
?>

In the example above, the Status enum can only be Status::DRAFT, Status::PUBLISHED, or Status::ARCHIVED. The setStatus function is guaranteed to receive one of these values.

Backed Enums

Backed enums are enums that are "backed" by a scalar value (either an int or a string). This is useful for storing the enum value in a database or other storage.

<?php
enum Status: string {
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';
}

echo Status::PUBLISHED->value; // 'published'

$status = Status::from('published'); // Status::PUBLISHED
$status = Status::tryFrom('unknown'); // null
?>

Key features of Backed Enums:

  • They must declare a scalar type (int or string).
  • All cases must have a unique scalar equivalent.
  • from() method: returns the Enum case corresponding to a scalar value. Throws a ValueError if the value is not found.
  • tryFrom() method: returns the Enum case or null if the value is not found.

Enums with Methods

Enums can also have methods, making them even more powerful.

<?php
enum Status: string {
    case DRAFT = 'draft';
    case PUBLISHED = 'published';
    case ARCHIVED = 'archived';

    public function label(): string {
        return match($this) {
            self::DRAFT => 'Draft',
            self::PUBLISHED => 'Published',
            self::ARCHIVED => 'Archived',
        };
    }
}

echo Status::PUBLISHED->label(); // 'Published'
?>