Enums
suggest changeAn enumeration (enum) is a type with a fixed, closed set of possible values. PHP has had native enums since PHP 8.1. Before that, the usual approach was a class full of constants, which doesn't stop anyone from passing the wrong value:
<?php
class OrderStatusConst
{
const PENDING = 'pending';
const SHIPPED = 'shipped';
}
function shipConst(string $status): void
{
echo "status: $status\n";
}
shipConst(OrderStatusConst::PENDING);
shipConst('banana'); // accepted, nothing stops it
Output:
status: pending
status: banana
With an enum the type of the parameter is the set of allowed values, and PHP rejects anything else.
Pure enums
A pure enum is declared with enum and lists its cases with case. Each case is a singleton object of the enum's type:
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
function describe(Suit $suit): string
{
return "Suit: " . $suit->name;
}
$s = Suit::Hearts;
echo describe($s), "\n";
var_dump($s === Suit::Hearts);
var_dump($s === Suit::Spades);
var_dump($s instanceof Suit);
var_dump($s instanceof UnitEnum);
foreach (Suit::cases() as $case) {
echo $case->name, " ";
}
echo "\n";
var_dump(Suit::Clubs);
try {
describe('Hearts');
} catch (TypeError $e) {
// drop the ", called in <file> on line N" part of the message
echo get_class($e), ": ", explode(', called', $e->getMessage())[0], "\n";
}
Output:
Suit: Hearts
bool(true)
bool(false)
bool(true)
bool(true)
Hearts Diamonds Clubs Spades
enum(Suit::Clubs)
TypeError: describe(): Argument #1 ($suit) must be of type Suit, string given
Things to note:
- you refer to a case as
EnumName::CaseName - every case has a read-only
nameproperty holding the case name as a string Enum::cases()returns all cases in declaration order- there is only ever one instance of each case, so compare cases with
=== - every enum automatically implements the built-in
UnitEnuminterface
Case names are ordinary identifiers. The convention used by the PHP manual and most projects is PascalCase.
Backed enums
A pure enum has no scalar representation. To store a case in a database, put it in a URL or send it as JSON, you need a backed enum: each case gets a unique int or string value.
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
}
enum Priority: int
{
case Low = 1;
case Normal = 5;
case High = 10;
}
echo Status::Published->name, " => ", Status::Published->value, "\n";
echo Priority::High->name, " => ", Priority::High->value, "\n";
$fromDb = 'archived';
$status = Status::from($fromDb);
var_dump($status);
var_dump(Status::tryFrom('deleted'));
try {
Status::from('deleted');
} catch (ValueError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
$p = Priority::tryFrom((int) ($_GET['p'] ?? 0)) ?? Priority::Normal;
echo "priority: {$p->name}\n";
var_dump(Status::Draft instanceof BackedEnum);
Output:
Published => published
High => 10
enum(Status::Archived)
NULL
ValueError: "deleted" is not a valid backing value for enum Status
priority: Normal
bool(true)
A backed enum adds:
- a read-only
valueproperty with the backing value from($value)which returns the matching case or throwsValueErrortryFrom($value)which returns the matching case ornull
Use from() when an invalid value is a bug (data you wrote yourself, e.g. a database column) and tryFrom() with ?? for untrusted input where you want a fallback. Backed enums implement the BackedEnum interface, which extends UnitEnum.
Rules for backed enums:
- the backing type must be
intorstring;floatand others are rejected - every case must have a value; you can't mix backed and pure cases
- values must be unique within the enum
- values must be literals or constant expressions, not function calls
<?php
enum S: float { case A = 1.5; }
Fatal error: Enum backing type must be int or string, float given in ...
Methods, static methods and constants
Enums can have methods. Inside a method $this is the current case, which makes match ($this) the natural way to attach data to each case:
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
public function label(): string
{
return match ($this) {
self::Draft => 'Draft (not visible)',
self::Published => 'Published',
self::Archived => 'Archived',
};
}
public function isVisible(): bool
{
return $this === self::Published;
}
public static function fromLabel(string $label): self
{
foreach (self::cases() as $case) {
if ($case->label() === $label) {
return $case;
}
}
throw new ValueError("unknown label: $label");
}
/** @return array<string, string> value => label, e.g. for a <select> */
public static function options(): array
{
$out = [];
foreach (self::cases() as $case) {
$out[$case->value] = $case->label();
}
return $out;
}
}
foreach (Status::cases() as $s) {
printf("%-10s %-20s visible=%s\n", $s->value, $s->label(), $s->isVisible() ? 'yes' : 'no');
}
var_dump(Status::fromLabel('Archived'));
print_r(Status::options());
Output:
draft Draft (not visible) visible=no
published Published visible=yes
archived Archived visible=no
enum(Status::Archived)
Array
(
[draft] => Draft (not visible)
[published] => Published
[archived] => Archived
)
Static methods are handy as named constructors (fromLabel()) or helpers that work on all cases (options()).
Interfaces, traits and constants
An enum can implement interfaces, use traits (as long as they don't declare properties) and declare constants. A constant can be an alias for a case or an array of cases:
<?php
interface HasColor
{
public function color(): string;
}
trait DescribesItself
{
public function describe(): string
{
return sprintf('%s::%s', self::class, $this->name);
}
}
enum Suit implements HasColor
{
use DescribesItself;
case Hearts;
case Diamonds;
case Clubs;
case Spades;
const Wild = self::Spades;
const RED = [self::Hearts, self::Diamonds];
public function color(): string
{
return in_array($this, self::RED, true) ? 'Red' : 'Black';
}
}
function isRed(HasColor $thing): bool
{
return $thing->color() === 'Red';
}
foreach (Suit::cases() as $suit) {
printf("%-15s %-6s red=%s\n", $suit->describe(), $suit->color(), isRed($suit) ? 'yes' : 'no');
}
var_dump(Suit::Wild);
var_dump(Suit::Wild === Suit::Spades);
Output:
Suit::Hearts Red red=yes
Suit::Diamonds Red red=yes
Suit::Clubs Black red=no
Suit::Spades Black red=no
enum(Suit::Spades)
bool(true)
Implementing an interface lets enum cases be passed anywhere that interface is expected, next to regular classes that implement it. See Interfaces and Traits.
Exhaustive handling with match
match and enums work well together: list every case and you get a value for each one. If a case is missing, match throws UnhandledMatchError at runtime instead of silently returning nothing (as a switch without default would):
<?php
enum Level
{
case Debug;
case Info;
case Error;
}
function color(Level $level): string
{
return match ($level) {
Level::Debug => 'gray',
Level::Info => 'blue',
// Level::Error forgotten
};
}
echo color(Level::Info), "\n";
try {
echo color(Level::Error), "\n";
} catch (\UnhandledMatchError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
Output:
blue
UnhandledMatchError: Unhandled match case Level::Error
PHP itself only detects the missing case when it happens. Static analysers such as PHPStan and Psalm report a non-exhaustive match over an enum before the code runs, which is a good reason to avoid a default arm: with default, adding a new case won't be flagged anywhere. More on match in Pattern matching.
Enums as defaults and in constant expressions
Enum cases are constant expressions, so they can be used as default parameter values, property defaults and in class constants. Since PHP 8.2 you can also read ->value and ->name in constant expressions. Since PHP 8.3 a case can be fetched dynamically with Enum::{$name}:
<?php
enum Size: string
{
case Small = 's';
case Medium = 'm';
case Large = 'l';
}
class Shirt
{
// enum cases work as default values and in constant expressions
const DEFAULT_SIZE = Size::Medium;
const DEFAULT_CODE = Size::Medium->value; // PHP 8.2+
public function __construct(
public readonly string $name,
public readonly Size $size = self::DEFAULT_SIZE,
) {}
}
$a = new Shirt('Plain');
$b = new Shirt('Logo', Size::Large);
echo "{$a->name}: {$a->size->name}\n";
echo "{$b->name}: {$b->size->name}\n";
echo Shirt::DEFAULT_CODE, "\n";
// dynamic access to a case by name
$name = 'Small';
var_dump(constant(Size::class . '::' . $name));
var_dump(Size::{$name}); // PHP 8.3+
Output:
Plain: Medium
Logo: Large
m
enum(Size::Small)
enum(Size::Small)
Fetching by name is useful for pure enums, which have no from(). Make sure the name is valid first (for example with defined(Size::class . '::' . $name)), because an unknown name throws an Error.
JSON and serialization
json_encode() encodes a backed enum case as its value. Decoding doesn't know about your enum, so convert back with from(). A pure enum has no scalar value and can't be JSON-encoded at all:
<?php
enum Status: string
{
case Active = 'active';
case Banned = 'banned';
}
enum Direction
{
case Up;
case Down;
}
$user = ['name' => 'alice', 'status' => Status::Active];
echo json_encode($user), "\n";
$decoded = json_decode('{"name":"bob","status":"banned"}', true);
$decoded['status'] = Status::from($decoded['status']);
var_dump($decoded['status']);
try {
json_encode(['dir' => Direction::Up], JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "JsonException: ", $e->getMessage(), "\n";
}
$s = serialize(Status::Banned);
echo $s, "\n";
var_dump(unserialize($s) === Status::Banned);
var_export(Direction::Down);
echo "\n";
Output:
{"name":"alice","status":"active"}
enum(Status::Banned)
JsonException: Non-backed enums have no default serialization
E:13:"Status:Banned";
bool(true)
\Direction::Down
serialize() has a dedicated E: format that stores the case name, and unserialize() returns the same singleton, so identity checks still work after a round trip. See JSON for more on encoding.
Enums in arrays
Cases are objects, which has a few consequences when you put them in arrays.
<?php
enum Suit
{
case Hearts;
case Spades;
}
enum Fruit: string
{
case Apple = 'apple';
case Pear = 'pear';
}
// backed enum: use ->value as array key
$stock = [Fruit::Apple->value => 10, Fruit::Pear->value => 3];
foreach ($stock as $key => $count) {
echo Fruit::from($key)->name, ": $count\n";
}
// any enum: WeakMap or SplObjectStorage keyed by the case object
$points = new WeakMap();
$points[Suit::Hearts] = 1;
$points[Suit::Spades] = 13;
foreach ($points as $suit => $pts) {
echo $suit->name, " => $pts\n";
}
// in_array and array_search need strict mode to compare identity
$hand = [Suit::Hearts, Suit::Hearts, Suit::Spades];
var_dump(in_array(Suit::Spades, $hand, true));
var_dump(array_search(Suit::Spades, $hand, true));
// array_unique() does not work on enums; filter by name instead
$unique = array_values(array_reduce($hand, function ($acc, $s) {
$acc[$s->name] = $s;
return $acc;
}, []));
echo count($unique), " unique\n";
var_dump(Suit::Hearts == Suit::Hearts, Suit::Hearts == Suit::Spades);
var_dump(Suit::Hearts < Suit::Spades, Suit::Hearts > Suit::Spades);
Output:
Apple: 10
Pear: 3
Hearts => 1
Spades => 13
bool(true)
int(2)
2 unique
bool(true)
bool(false)
bool(false)
bool(false)
Points to remember:
- a case can't be an array key directly (
[Suit::Hearts => 'red']throwsTypeError: Cannot access offset of type Suit on array). Use->valueor->nameas the key, or useWeakMap/SplObjectStorage - enums can't be converted to strings, so
array_unique(),sort()with default flags, string interpolation ("$suit") and(string)casts fail withObject of class Suit could not be converted to string - cases have no order:
<and>always returnfalse. If you need ordering, back the enum withintand compare->value, or add a method that returns a rank
array_column() reads the name and value properties, which gives you a quick lookup table:
<?php
enum Status: int
{
case Active = 1;
case Inactive = 0;
}
var_dump(array_column(Status::cases(), 'value', 'name'));
Output:
array(2) {
["Active"]=>
int(1)
["Inactive"]=>
int(0)
}
What enums can't do
Enums are deliberately restricted compared to classes. Cases carry no state of their own and there is exactly one instance of each:
<?php
enum Suit
{
case Hearts;
case Spades;
}
$tries = [
'new' => fn() => new Suit(),
'clone' => fn() => clone Suit::Hearts,
'property' => function () { $s = Suit::Hearts; $s->extra = 1; },
'name' => function () { $s = Suit::Hearts; $s->name = 'X'; },
'key' => fn() => [Suit::Hearts => 'red'],
];
foreach ($tries as $label => $fn) {
try {
$fn();
echo "$label: ok\n";
} catch (Error $e) {
echo "$label: ", get_class($e), ": ", $e->getMessage(), "\n";
}
}
Output:
new: Error: Cannot instantiate enum Suit
clone: Error: Trying to clone an uncloneable object of class Suit
property: Error: Cannot create dynamic property Suit::$extra
name: Error: Cannot modify readonly property Suit::$name
key: TypeError: Cannot access offset of type Suit on array
These are compile-time errors:
- declaring properties (
Enum Suit cannot include properties); use methods withmatchinstead extends: an enum can't extend a class or another enum, and nothing can extend an enum- a constructor, destructor, or magic methods other than
__call,__callStaticand__invoke - a backed case without a value (
Case B of backed enum S must have a value)
Duplicate backing values are reported with Error: Duplicate value in enum S for cases A and B when the enum is first used, not when the file is compiled.
Reflection and introspection
enum_exists() checks whether a name is an enum, and ReflectionEnum gives details about its cases:
<?php
enum Status: int
{
case Active = 1;
case Inactive = 0;
}
var_dump(enum_exists(Status::class));
var_dump(Status::Active instanceof UnitEnum);
$r = new ReflectionEnum(Status::class);
echo "backed: ", $r->isBacked() ? 'yes' : 'no', "\n";
echo "type: ", $r->getBackingType(), "\n";
foreach ($r->getCases() as $case) {
echo $case->getName(), " = ", var_export($case->getBackingValue(), true), "\n";
}
Output:
bool(true)
bool(true)
backed: yes
type: int
Active = 1
Inactive = 0
Note that class_exists() also returns true for enums, because an enum is a special kind of class. See Reflection.
Practical example: a state machine
Enums are a good fit for state machines. The enum lists the states and knows which transitions are allowed; the entity stores the current state and refuses illegal moves:
<?php
enum OrderState: string
{
case New = 'new';
case Paid = 'paid';
case Shipped = 'shipped';
case Delivered = 'delivered';
case Cancelled = 'cancelled';
/** @return list<self> */
public function allowedNext(): array
{
return match ($this) {
self::New => [self::Paid, self::Cancelled],
self::Paid => [self::Shipped, self::Cancelled],
self::Shipped => [self::Delivered],
self::Delivered, self::Cancelled => [],
};
}
public function canTransitionTo(self $next): bool
{
return in_array($next, $this->allowedNext(), true);
}
public function isFinal(): bool
{
return $this->allowedNext() === [];
}
}
final class Order
{
private OrderState $state = OrderState::New;
public function __construct(public readonly int $id) {}
public function state(): OrderState
{
return $this->state;
}
public function moveTo(OrderState $next): void
{
if (!$this->state->canTransitionTo($next)) {
throw new LogicException(sprintf(
'order %d: cannot go from %s to %s',
$this->id, $this->state->value, $next->value
));
}
echo "order {$this->id}: {$this->state->value} -> {$next->value}\n";
$this->state = $next;
}
}
$order = new Order(42);
$order->moveTo(OrderState::Paid);
$order->moveTo(OrderState::Shipped);
try {
$order->moveTo(OrderState::Cancelled);
} catch (LogicException $e) {
echo "error: ", $e->getMessage(), "\n";
}
$order->moveTo(OrderState::Delivered);
var_dump($order->state()->isFinal());
// store and load the state as a plain string
$row = ['id' => $order->id, 'state' => $order->state()->value];
echo json_encode($row), "\n";
$loaded = OrderState::from($row['state']);
var_dump($loaded === OrderState::Delivered);
Output:
order 42: new -> paid
order 42: paid -> shipped
error: order 42: cannot go from shipped to cancelled
order 42: shipped -> delivered
bool(true)
{"id":42,"state":"delivered"}
bool(true)
The string values are what goes into the database column. Pick them carefully and don't change them later: renaming a case is a safe refactoring, but changing its backing value makes existing rows unreadable by from().
Guidelines
- Use an enum whenever a value must be one of a known, fixed set: statuses, roles, units, directions, log levels.
- Use a pure enum when the values never leave your PHP code; use a backed enum when they are stored or sent somewhere.
- Prefer
stringbacking values for data that people read (database dumps, JSON, logs);intvalues are compact but meaningless without the code. - Put behaviour on the enum (
label(),color(),allowedNext()) instead of scatteringswitchstatements around the code base. - Compare cases with
===, and passtrueas the strict flag toin_array()andarray_search(). - Convert at the boundaries:
from()/tryFrom()when reading input,->valuewhen writing output.