Lesson 6 of 7
Enums (PHP 8.1+)
PHP 8.1 introduced native Enums - a first-class type for representing a fixed set of values. Enums replace the old class-with-constants pattern, provide type safety, and can have methods and implement interfaces. Backed enums attach scalar values (string/int) to each case.
Pure & Backed Enums with Methods
<?php
declare(strict_types=1);
// ── Pure enum - no backing value ──────────────────────────────
enum Status {
case Draft;
case Published;
case Archived;
public function label(): string {
return match($this) {
Status::Draft => "Draft",
Status::Published => "Published",
Status::Archived => "Archived",
};
}
public function canTransitionTo(Status $new): bool {
return match($this) {
Status::Draft => $new === Status::Published,
Status::Published => $new === Status::Archived,
Status::Archived => false,
};
}
}
// ── Backed enum - with string values (DB storage, API) ────────
enum Role: string {
case Guest = "guest";
case Author = "author";
case Editor = "editor";
case Admin = "admin";
public function hasPermission(string $permission): bool {
$permissions = [
"guest" => [],
"author" => ["create_post", "edit_own_post"],
"editor" => ["create_post", "edit_any_post", "publish_post"],
"admin" => ["create_post", "edit_any_post", "publish_post", "delete_post", "manage_users"],
];
return in_array($permission, $permissions[$this->value], true);
}
}
// ── Using backed enum ─────────────────────────────────────────
$role = Role::from("editor"); // Role::Editor - throws ValueError if invalid
$role = Role::tryFrom("editor"); // Role::Editor - returns null if invalid
$role = Role::tryFrom("superuser"); // null - safe
echo $role?->value; // "editor"
var_dump(Role::Author->hasPermission("create_post")); // true
// ── Enum in class ─────────────────────────────────────────────
class Post2 {
public function __construct(
public readonly string $title,
private Status $status = Status::Draft,
private Role $authorRole = Role::Author,
) {}
public function publish(): void {
if (!$this->status->canTransitionTo(Status::Published)) {
throw new LogicException("Cannot publish from {$this->status->label()} state.");
}
$this->status = Status::Published;
}
}
// ── Enums implement interfaces ─────────────────────────────────
interface HasLabel { public function label(): string; }
enum PostType: string implements HasLabel {
case Article = "article";
case Tutorial = "tutorial";
case Reference = "reference";
public function label(): string { return ucfirst($this->value); }
}
// ── List all cases (useful for select boxes) ──────────────────
$allStatuses = Status::cases(); // [Status::Draft, Status::Published, Status::Archived]
$statusOptions = array_map(fn($s) => ["value" => $s->name, "label" => $s->label()], $allStatuses);Quick Quiz
Tip
Tip
Practice Enums PHP 81 in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Enums (PHP 8.1+)
Practice Task
Note
Practice Task - (1) Write a working example of Enums PHP 81 from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Enums PHP 81 is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?