PHP Fibers explained: what they are, how they work, when to use them
PHP 8.1 Fibers let a function pause and resume without returning. Here is how start, suspend and resume pass values, how Fibers differ from generators and threads, and where they help in real code.
On this page
A Fiber is a function that can pause itself in the middle, hand control back to whoever started it, and later carry on from exactly where it stopped, with all its local variables intact. Fibers arrived in PHP 8.1. They do not run code in parallel: one thing runs at a time, and the code decides when to switch. That is called cooperative multitasking.
You will rarely write new Fiber in application code. Fibers are a building block for async libraries and event loops, which use them so that asynchronous code can be written in a normal, top-to-bottom style. Knowing how they work helps you read those libraries and debug them.
The four calls you need
$fiber = new Fiber(function (string $greeting): string {
echo "$greeting from inside\n";
$reply = Fiber::suspend('paused'); // hand 'paused' to the caller, wait
echo "resumed with: $reply\n";
return 'done';
});
$value = $fiber->start('Hello'); // runs until the first suspend; $value === 'paused'
echo "caller got: $value\n";
$fiber->resume('carry on'); // continues after the suspend
echo $fiber->getReturn(); // done
Output:
Hello from inside
caller got: paused
resumed with: carry on
done
new Fiber(callable)creates the fiber. Nothing runs yet.$fiber->start(...$args)runs it until it suspends or finishes. It returns the value passed toFiber::suspend(), ornullif the fiber finished.Fiber::suspend($value)pauses the current fiber from anywhere inside it, however deep in the call stack. When resumed, it returns the value passed toresume().$fiber->resume($value)continues a suspended fiber.$fiber->throw($exception)resumes it by throwing inside it instead.
State checks: isStarted(), isSuspended(), isRunning(), isTerminated(). getReturn() gives the return value once the fiber has terminated.
Fibers vs generators
Generators (yield, PHP 5.5) can also pause and resume, but only at the yield in the generator function itself. Any function that wants to pause has to be a generator, and so does every function that calls it. That “colours” the whole call stack.
A Fiber can suspend from any depth. A database client deep in your code can call Fiber::suspend() while it waits for a socket, and none of the functions above it need to change their signature or know that pausing happened. That is the whole point: async without changing the functions in between.
Fibers vs threads and processes
| Fibers | Threads (parallel extension) | Processes (pcntl, queues) | |
|---|---|---|---|
| Runs at the same time | No, one at a time | Yes | Yes |
| Switches when | The code calls suspend | The OS decides | The OS decides |
| Shared memory | Yes, same process | Limited | No |
| Good for | Waiting on I/O | CPU-heavy work | Isolation, background jobs |
A CPU-bound loop inside a Fiber blocks everything else until it suspends. Fibers make waiting efficient; they do not make computation faster.
A tiny scheduler
Event loops keep a queue of fibers and resume whichever one has something to do. This toy version just takes turns:
final class Scheduler
{
/** @var SplQueue<Fiber> */
private SplQueue $queue;
public function __construct() { $this->queue = new SplQueue(); }
public function spawn(callable $task): void
{
$this->queue->enqueue(new Fiber($task));
}
public function run(): void
{
while (!$this->queue->isEmpty()) {
$fiber = $this->queue->dequeue();
$fiber->isStarted() ? $fiber->resume() : $fiber->start();
if (!$fiber->isTerminated()) {
$this->queue->enqueue($fiber);
}
}
}
}
$s = new Scheduler();
foreach (['A', 'B'] as $name) {
$s->spawn(function () use ($name) {
for ($i = 1; $i <= 3; $i++) {
echo "$name$i ";
Fiber::suspend();
}
});
}
$s->run(); // A1 B1 A2 B2 A3 B3
Real event loops resume a fiber only when its socket is readable or its timer has fired, which is what lets one PHP process handle many slow network calls at once.
Where Fibers show up in practice
- Async frameworks and event loops. Modern async PHP libraries are built on Fibers, so you can write
$response = $client->get($url);and the library suspends the current fiber while the request is in flight. - Long-running servers. Application servers that keep PHP in memory use Fibers or similar coroutines to serve many connections per worker.
- Concurrent HTTP or database calls in a script. Fetching ten APIs concurrently instead of one after another, through an async client.
- Testing and tooling. Some test tools use Fibers to pause code at a precise point.
For a typical request/response web app, you get the benefit through libraries, not by writing Fibers yourself.
Pitfalls
- Blocking calls block everything.
sleep(),file_get_contents()on a URL, and PDO queries do not suspend a fiber. In an async app, use the library’s non-blocking equivalents. - Resuming in the wrong state throws a
FiberError: starting twice, resuming a running fiber or one that never started, or callingFiber::suspend()outside a fiber. - Exceptions thrown inside a fiber come out of the
start()orresume()call that was running it. Catch them there. - Debugging. Stack traces show the fiber’s stack, which can look odd at first. Xdebug supports Fibers.
Fibers need PHP 8.1 or later. The PHP version checker flags new Fiber and Fiber::suspend() when it scans your code, and supported PHP versions shows which releases still get fixes.