PHP Fibers: Practical Concurrency Without Callbacks

PHP Fibers: Practical Concurrency Without Callbacks

PHP Fibers: Practical Concurrency Without Callbacks

PHP Fibers (introduced in PHP 8.1) are a low-level concurrency primitive that allow execution to be paused and resumed within a single thread. They power modern async PHP frameworks including ReactPHP and Revolt.

How Fibers Work

$fiber = new Fiber(function (): void {
    $value = Fiber::suspend('first');
    echo "Resumed with: {$value}\n";
});

$first = $fiber->start();      // runs until suspend()
$fiber->resume('hello');      // resumes, prints "Resumed with: hello"

Unlike generators, fibers can be suspended from anywhere in the call stack, not just at the top level.

Practical Use: Async HTTP

Libraries like amphp/http-client use fibers under the hood so you can write sequential-looking code that is non-blocking:

$response = $client->request(new Request('https://api.example.com/users'));
$body = $response->getBody()->buffer();

No callbacks, no ->then() chains — the fiber suspends while waiting for I/O and resumes transparently.

All Comments