ZetCode

PHP enum Keyword

last modified November 25, 2026

The PHP enum keyword declares a type with a fixed set of named cases. Enums give a name and a type to a closed set of values, replacing loose string and integer constants with something the type system can check.

This article covers pure and backed enums, from and tryFrom, cases(), methods, static factories, constants, interfaces, JSON serialization, and the rules that follow from the singleton model.

Basic definitions

An enum declares a type with a fixed, closed set of named cases. Each case is a singleton object of that enum type: HttpMethod::Post is the only instance of the Post case, and two references to it are identical.

A pure enum stores no value; it is useful when the case name is the whole information. A backed enum adds an int or string value to every case, which is useful at boundaries such as a database column, a URL parameter, or JSON. Backed values must be unique and must be constant expressions of the declared type.

Enums are classes in most respects. They can have methods, static methods, constants, and they can implement interfaces. They cannot have properties, cannot be instantiated with new, cannot be extended, and cannot be cloned. PHP 8.1 introduced them. The final keyword article explains why an enum is implicitly final, and match covers the expression often used inside enum methods.

The syntax is enum Name { case A; case B; } for a pure enum and enum Name: string { case A = "a"; } for a backed one. Case names are usually PascalCase.

A pure enum

The first example models the HTTP methods that a small router understands. The cases are the complete list of values the type accepts.

enum_basic.php
<?php

declare(strict_types=1);

enum HttpMethod
{
    case Get;
    case Post;
    case Put;
    case Delete;
}

$method = HttpMethod::Post;

echo $method->name, "\n";
var_dump($method === HttpMethod::Post);
var_dump($method === HttpMethod::Get);

The cases are objects, and ->name returns the case name as a string. The strict comparisons show identity: the stored case is the same object as HttpMethod::Post, and not the Get case. There is no way to create a fourth value at runtime; the type is closed.

$ php enum_basic.php
Post
bool(true)
bool(false)

Backed enums

A backed enum attaches a scalar value to each case. The backing type is declared after the enum name, and every case must supply a unique value of that type.

enum_backed.php
<?php

declare(strict_types=1);

enum Status: string
{
    case Pending = "pending";
    case Approved = "approved";
    case Rejected = "rejected";
}

$status = Status::Approved;

echo $status->name, "\n";
echo $status->value, "\n";

The backing value is read with ->value, while ->name stays available. The values are strings here, but an enum can be backed by int instead. PHP checks that the values are unique and that the type matches the declaration.

$ php enum_backed.php
Approved
approved

from and tryFrom

A backed enum has two built-in conversion methods. from returns the case for a backing value and throws when the value is unknown; tryFrom returns the case or null.

enum_from.php
<?php

declare(strict_types=1);

enum Status: string
{
    case Pending = "pending";
    case Approved = "approved";
}

$status = Status::from("approved");
echo $status->name, "\n";

$unknown = Status::tryFrom("archived");
var_dump($unknown);

try {
    Status::from("archived");
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";
}

from converts a backing value into the case and throws ValueError when the value is not listed. tryFrom is the quiet version, which is convenient for untrusted input. The lookup is case-sensitive, so "Approved" would not match "approved". The ValueError article covers the exception type.

$ php enum_from.php
Approved
NULL
"archived" is not a valid backing value for enum Status

Listing the cases

Every enum has a static cases() method. It returns all cases in declaration order, which is the order a form or a documentation table should use.

enum_cases.php
<?php

declare(strict_types=1);

enum Suit: string
{
    case Hearts = "H";
    case Diamonds = "D";
    case Clubs = "C";
    case Spades = "S";
}

foreach (Suit::cases() as $suit) {
    echo $suit->name, "=", $suit->value, "\n";
}

echo count(Suit::cases()), "\n";

cases() returns all cases in declaration order. The loop prints the name and value of each one, and count confirms there are four. This is the usual way to build a select box, a validation list, or a test matrix without duplicating the case names.

$ php enum_cases.php
Hearts=H
Diamonds=D
Clubs=C
Spades=S
4

Methods on an enum

An enum can have instance methods. Inside a method, $this is the case object, so the method can use match ($this) to choose behavior.

enum_methods.php
<?php

declare(strict_types=1);

enum Direction
{
    case North;
    case South;
    case East;
    case West;

    public function opposite(): self
    {
        return match ($this) {
            self::North => self::South,
            self::South => self::North,
            self::East => self::West,
            self::West => self::East,
        };
    }
}

echo Direction::North->opposite()->name, "\n";

The method returns another case and declares self as its return type. match ($this) lists every case, so adding a new direction without updating the method raises UnhandledMatchError at runtime. That is a useful guard: the method cannot silently fall through to a wrong default. The match expression article covers the expression form in depth.

$ php enum_methods.php
South

Static factory methods

A static method can build a case from a value that is not the backing value, such as a form label or a legacy code.

enum_static.php
<?php

declare(strict_types=1);

enum Size: int
{
    case Small = 1;
    case Medium = 2;
    case Large = 3;

    public static function fromLabel(string $label): self
    {
        return match (strtolower($label)) {
            "small" => self::Small,
            "medium" => self::Medium,
            "large" => self::Large,
            default => throw new ValueError("Unknown size: $label"),
        };
    }
}

echo Size::fromLabel("Medium")->name, "\n";

The factory maps a human-readable label to a case and throws ValueError for an unknown label. The built-in from already covers exact backing values; a custom factory is for looser input such as a form field. The return type self keeps the method inside the enum.

$ php enum_static.php
Medium

Enum constants

Enums may declare constants, and a constant can hold one of the cases. This gives a named default without a separate global variable.

enum_constants.php
<?php

declare(strict_types=1);

enum Planet: string
{
    case Earth = "earth";
    case Mars = "mars";

    public const DEFAULT = self::Earth;

    public function gravity(): float
    {
        return match ($this) {
            self::Earth => 9.81,
            self::Mars => 3.72,
        };
    }
}

echo Planet::DEFAULT->value, "\n";
echo Planet::Mars->gravity(), "\n";

Enum constants are ordinary class constants, but they can hold cases. DEFAULT points at Planet::Earth, and a method called through it works like any other case. Constants are useful for a documented default that belongs to the enum itself.

$ php enum_constants.php
earth
3.72

Implementing an interface

An enum can implement an interface and can be type-hinted through it. This lets an enum join an existing API without exposing the concrete enum type.

enum_interface.php
<?php

declare(strict_types=1);

interface HasLabel
{
    public function label(): string;
}

enum Priority: int implements HasLabel
{
    case Low = 1;
    case High = 2;

    public function label(): string
    {
        return match ($this) {
            self::Low => "low priority",
            self::High => "high priority",
        };
    }
}

function describe(HasLabel $item): string
{
    return $item->label();
}

echo describe(Priority::High), "\n";
var_dump(Priority::High instanceof HasLabel);

The enum implements HasLabel, so it can be passed to any function that accepts that interface. instanceof confirms the relationship at runtime. The method is implemented once for the enum, and the interface keeps the caller independent of the concrete enum type. The interface keyword and implements keyword articles cover the contract.

$ php enum_interface.php
high priority
bool(true)

Enums and JSON

A backed enum serializes to its backing value, which is usually what an API should send. A pure enum has no default representation.

enum_json.php
<?php

declare(strict_types=1);

enum Suit: string
{
    case Hearts = "H";
    case Spades = "S";
}

enum Direction
{
    case North;
    case South;
}

echo json_encode(Suit::Hearts), "\n";

$json = json_encode(Direction::North);
var_dump($json);
echo json_last_error_msg(), "\n";

A backed enum serializes to its backing value, so Suit::Hearts becomes "H". A pure enum has no default representation: json_encode returns false and sets the error message shown above. Store ->value explicitly when the JSON shape must be stable, and convert the decoded string back with from or tryFrom. The JSON article covers the flags and error handling.

$ php enum_json.php
"H"
bool(false)
Non-backed enums have no default serialization

Enums cannot have properties

A case is a singleton, so per-case mutable state would be shared by every user of the case. PHP rejects properties in an enum outright.

enum_property.php
<?php

declare(strict_types=1);

enum Direction
{
    case North;

    public string $label = "north";
}

PHP rejects the declaration with Enum Direction cannot include properties. An enum case is a singleton, so per-case mutable state would be shared by every user of the case. Store related data in a method, a constant, or a separate object instead.

$ php enum_property.php
Fatal error: Enum Direction cannot include properties in /app/enum_property.php on line 9
Stack trace:
#0 {main}

Rules and limitations

The remaining restrictions follow from the singleton model.

Best practices

An enum is a type, not a bag of constants. Treat its cases as the complete vocabulary of the domain concept.

Source

PHP manual: enumerations

PHP manual: backed enumerations

PHP manual: enum methods and constants

This article covered the PHP enum keyword: pure and backed enums, conversion with from and tryFrom, cases(), methods, constants, interfaces, JSON, and the restrictions of the singleton model. Continue with PHP match keyword for the expression used inside enum methods, or read PHP final keyword and PHP interface keyword for the modifiers enums rely on.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.