Home » Releases » PHP 8.1 »

PHP 8.1 Code Comparisons

Explore PHP 8.1

Enumerations

PHP 8.1 introduces native Enumerations (Enums). Enums allow developers to define a domain of permitted values for a property or variable, supporting methods, interfaces, and scalar backing.
Before PHP 8.1
class Status
{
    public const PENDING = 'pending';
    public const ACTIVE = 'active';
}

$status = Status::ACTIVE;
PHP 8.1 or Later
enum Status: string
{
    case Pending = 'pending';
    case Active = 'active';
}

$status = Status::Active;

Fibers

PHP 8.1 introduces Fibers, low-level primitives for managing concurrency and cooperative multitasking. Fibers allow interruptible execution stacks, making async programming libraries possible without complex generator chains.
PHP 8.1 or Later
$fiber = new Fiber(function (): void {
    $value = Fiber::suspend('paused');
    echo "Resumed with: {$value}\n";
});

$output = $fiber->start();
echo "Status: {$output}\n";
$fiber->resume('ready');

Readonly Properties

PHP 8.1 adds support for readonly properties. Once assigned, a readonly property cannot be modified, enforcing immutability directly at the language level without verbose getters.
Before PHP 8.1
class User
{
    private string $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function getName(): string
    {
        return $this->name;
    }
}
PHP 8.1 or Later
class User
{
    public function __construct(
        public readonly string $name
    ) {}
}

First-Class Callable Syntax

PHP 8.1 introduces first-class callable syntax, using `callable(...)` to create Closure objects from methods, functions, and closures, replacing `Closure::fromCallable()` and string callables.
Before PHP 8.1
$fn = Closure::fromCallable('strlen');
$length = $fn('test');
PHP 8.1 or Later
$fn = strlen(...);
$length = $fn('test');