Skip to content

PHP 8.1 Enums and Fibers — Complete Guide to Modern PHP Features

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about PHP 8.1 Enums and Fibers. We cover key concepts, practical examples, and best practices to help you master this topic.

PHP 8.1 introduced native enumerations (enums) for fixed value sets and fibers for cooperative multitasking, enabling cleaner code and concurrent execution patterns.

What You'll Learn

By the end of this tutorial, you'll create backed and pure enums, add methods to enum cases, use fibers for cooperative multitasking, and integrate fiber-based concurrency in PHP.

Why Enums and Fibers Matter

Enums replace stringly-typed constants with compiler-checked values. Fibers enable async-like patterns without external libraries, useful for concurrent I/O operations.

Real-World Use

An e-commerce platform uses enums for order status (Pending, Confirmed, Shipped, Delivered) and fibers to concurrently fetch product data from multiple suppliers.

Enum Fibers Path

flowchart LR
  A[PHP 8 Features] --> B[Enums/Fibers]
  B --> C[Readonly Classes]
  B --> D[PSR Standards]
  C --> E[Property Hooks]
  B --> F{You Are Here}
  style F fill:#f90,color:#fff

Pure Enums

Pure enums define cases without associated values.

<?php
enum OrderStatus {
    case Pending;
    case Confirmed;
    case Shipped;
    case Delivered;
    case Cancelled;
}
function sendNotification(OrderStatus $status): void {
    match ($status) {
        OrderStatus::Confirmed => echo "Order confirmed\n",
        OrderStatus::Shipped => echo "Order shipped\n",
        OrderStatus::Delivered => echo "Order delivered\n",
        default => echo "Status: {$status->name}\n",
    };
}
sendNotification(OrderStatus::Shipped);

Backed Enums

Backed enums have scalar values (int or string) for database persistence.

<?php
enum UserRole: string {
    case Admin = "admin";
    case Editor = "editor";
    case Viewer = "viewer";
    public function label(): string {
        return match ($this) {
            self::Admin => "Administrator",
            self::Editor => "Content Editor",
            self::Viewer => "Read Only",
        };
    }
    public static function fromDatabase(string $value): self {
        return self::from($value);
    }
}
$role = UserRole::from("editor");
echo $role->label();
echo $role->value;

Enum Methods

Enums can have methods, implement interfaces, and use traits.

<?php
interface HasColor { public function color(): string; }
enum PaymentMethod: string implements HasColor {
    case CreditCard = "cc";
    case DebitCard = "dc";
    case PayPal = "pp";
    case BankTransfer = "bt";
    public function color(): string {
        return match ($this) {
            self::CreditCard => "#4A90D9",
            self::DebitCard => "#7B68EE",
            self::PayPal => "#003087",
            self::BankTransfer => "#2E8B57",
        };
    }
    public function isInstant(): bool {
        return $this === self::CreditCard || $this === self::DebitCard;
    }
}
echo PaymentMethod::PayPal->color();
echo PaymentMethod::CreditCard->isInstant() ? "Instant" : "Delayed";

Fiber Basics

Fibers are cooperative concurrency primitives that can suspend and resume execution.

<?php
function fetchData(string $url): string {
    $fiber = new Fiber(function () use ($url): string {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    });
    return $fiber->start();
}

Fiber Scheduling

Multiple fibers can be scheduled to run concurrently, suspending with Fiber::suspend().

<?php
function fetchMultiple(array $urls): array {
    $fibers = [];
    $results = [];
    foreach ($urls as $key => $url) {
        $fibers[$key] = new Fiber(function () use ($url) {
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        });
        $fibers[$key]->start();
    }
    foreach ($fibers as $key => $fiber) {
        $results[$key] = $fiber->getReturn();
    }
    return $results;
}

Common Mistakes

1. Comparing Enums Incorrectly

Enums are objects. Use === for comparison, not == which may cause unexpected matches.

2. Serializing Backed Enums to Database Incorrectly

Use $enum->value for backing values and self::from() to reconstruct from the database.

3. Not Handling Fiber Throw

Call Fiber::throw() to rethrow exceptions from the fiber's context.

4. Creating Too Many Fibers

Each fiber has memory overhead. Limit concurrent fibers to a reasonable pool size.

5. Forgetting Enums Cannot Extend Other Classes

Enums cannot extend classes but can implement interfaces and use traits.

Practice Questions

1. What is the difference between pure and backed enums?

Pure enums have no associated values. Backed enums are backed by int or string values.

2. Can enums have methods?

Yes. Enums can have methods, implement interfaces, and use traits.

3. What is a fiber in PHP 8.1?

A cooperative concurrency primitive that can suspend execution and resume later.

4. How do you get the backing value of an enum case?

$enum->value returns the backing value. $enum->name returns the case name as a string.

5. Challenge: Create a role-based authorization system using enums.

<?php
enum Permission: string {
    case Read = "read";
    case Write = "write";
    case Delete = "delete";
    case Admin = "admin";
}
enum Role: string {
    case Admin = "admin";
    case Editor = "editor";
    case Viewer = "viewer";
    public function permissions(): array {
        return match ($this) {
            self::Admin => Permission::cases(),
            self::Editor => [Permission::Read, Permission::Write],
            self::Viewer => [Permission::Read],
        };
    }
    public function has(Permission $perm): bool {
        return in_array($perm, $this->permissions());
    }
}
$role = Role::Admin;
echo $role->has(Permission::Delete) ? "Allowed" : "Denied";

FAQ

Can I serialize enums?

Yes. Use serialize() and unserialize(). Backed enums also work with json_encode producing the backing value.

What is the difference between fibers and threads?

Fibers are cooperative (voluntary suspension). Threads are preemptive (OS-scheduled). PHP does not have native threads.

Can enums implement interfaces?

Yes. Enums can implement any interface, making them compatible with dependency injection and type hints.

Do fibers improve performance?

For I/O-bound concurrent operations, fibers reduce overhead compared to sequential execution. Not for CPU-bound tasks.

How do I iterate over all enum cases?

ClassName::cases() returns an array of all defined cases.

Mini Project: Enum-Based State Machine

Build a state machine using PHP 8.1 enums.

<?php
enum OrderState: string {
    case Pending = "pending";
    case Paid = "paid";
    case Shipped = "shipped";
    case Delivered = "delivered";
    case Cancelled = "cancelled";
    public function allowedTransitions(): array {
        return match ($this) {
            self::Pending => [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->allowedTransitions(), true);
    }
}

What's Next

PHP 8.2 Readonly Classes PHP 8.3 JSON Validation PHP 8.4 Property Hooks

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro