PHP Enums
Many values in a program can only be one of a small, fixed set: an order status, a card suit, a day of the week. Before PHP 8.1 people used strings or class constants for these, which allowed typos like "shiped" to slip through. Enumerations (enums) make the set of allowed values a real type, checked by PHP.
A pure enum
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
function colour(Suit $s): string
{
return match ($s) {
Suit::Hearts, Suit::Diamonds => "red",
Suit::Clubs, Suit::Spades => "black",
};
}
$card = Suit::Diamonds;
echo $card->name, " is ", colour($card), "\n";
var_dump($card === Suit::Diamonds);
var_dump($card instanceof Suit);
echo count(Suit::cases()), " suits\n";Diamonds is red
bool(true)
bool(true)
4 suits
Each case is a singleton object: Suit::Diamonds === Suit::Diamonds is always true. The name property holds the case name as a string, and cases() returns all cases in declaration order.
Tip:
matchand enums are a perfect pair. If you forget a case,matchthrows anUnhandledMatchErrorinstead of silently doing nothing.
Backed enums
A backed enum gives every case a scalar value — int or string — which is what you store in a database or send as JSON.
<?php
enum Status: string
{
case Draft = 'draft';
case Published = 'published';
case Archived = 'archived';
}
echo Status::Published->value, "\n";
$fromDb = Status::from('archived');
echo $fromDb->name, "\n";
$maybe = Status::tryFrom('deleted');
var_dump($maybe);
try {
Status::from('deleted');
} catch (ValueError $e) {
echo get_class($e), ": ", $e->getMessage(), "\n";
}
echo json_encode(['status' => Status::Draft]), "\n";published
Archived
NULL
ValueError: "deleted" is not a valid backing value for enum Status
{"status":"draft"}
| Method / property | Pure enum | Backed enum |
|---|---|---|
->name |
yes | yes |
->value |
no | yes |
::cases() |
yes | yes |
::from($v) |
no | yes — throws ValueError if unknown |
::tryFrom($v) |
no | yes — returns null if unknown |
Methods, interfaces and constants
Enums can have methods (including static ones), implement interfaces and declare constants. They cannot have properties that change, and you cannot create them with new.
<?php
interface HasLabel
{
public function label(): string;
}
enum OrderStatus: int implements HasLabel
{
case Pending = 1;
case Shipped = 2;
case Delivered = 3;
case Cancelled = 9;
const DEFAULT = self::Pending;
public function label(): string
{
return match ($this) {
self::Pending => '⏳ Waiting for payment',
self::Shipped => '🚚 On its way',
self::Delivered => '✅ Delivered',
self::Cancelled => '❌ Cancelled',
};
}
public function isFinal(): bool
{
return $this === self::Delivered || $this === self::Cancelled;
}
public static function active(): array
{
return array_filter(self::cases(), fn($s) => !$s->isFinal());
}
}
foreach (OrderStatus::cases() as $s) {
printf("%-9s %d %s%s\n", $s->name, $s->value, $s->label(), $s->isFinal() ? " (final)" : "");
}
echo "Default: ", OrderStatus::DEFAULT->name, "\n";
echo "Active: ", implode(", ", array_map(fn($s) => $s->name, OrderStatus::active())), "\n";Pending 1 ⏳ Waiting for payment
Shipped 2 🚚 On its way
Delivered 3 ✅ Delivered (final)
Cancelled 9 ❌ Cancelled (final)
Default: Pending
Active: Pending, Shipped
Enums as type-safe parameters
Because an enum is a type, a function can demand exactly one of its cases. Passing a plain string is rejected with a TypeError.
<?php
enum Size: string
{
case Small = 'S';
case Medium = 'M';
case Large = 'L';
public function price(): float
{
return match ($this) {
self::Small => 2.50,
self::Medium => 3.20,
self::Large => 3.90,
};
}
}
function order(string $drink, Size $size): string
{
return "$drink ({$size->value}) costs " . number_format($size->price(), 2);
}
echo order("Latte", Size::Large), "\n";
echo order("Tea", Size::from('S')), "\n";
try {
echo order("Mocha", 'M');
} catch (TypeError $e) {
echo "TypeError caught\n";
}Latte (L) costs 3.90
Tea (S) costs 2.50
TypeError caught
Note: Enum cases are objects but not regular class instances: you cannot
clonethem, add properties, or compare them with<and>. Compare with===, or compare their->valuewhen you need ordering.
Test yourself
Which method returns null instead of throwing when the value is unknown?
from()tryFrom()cases()value()
What does Suit::cases() return?
- The number of cases
- An array of all case objects in declaration order
- An array of case names as strings
- The first case
Which property exists only on backed enums?
namevaluecasesclass