2 min read

PHP Fibers

Fibers are a low-level mechanism for managing parallelism in PHP. They are a form of lightweight, user-land cooperative multitasking. A Fiber is essentially a block of code that can be paused and resumed.

Fibers were introduced in PHP 8.1.

What are Fibers?

  • Interruptible Functions: You can think of Fibers as functions that can be paused from within, and then resumed from the point they were paused.
  • Cooperative Multitasking: Unlike preemptive multitasking (like threads), Fibers yield control voluntarily. A Fiber must explicitly pause itself to allow other code to run.
  • Not Threads: Fibers are not threads. They do not run in parallel. When a Fiber is running, the main thread of execution is blocked.

Basic Usage

<?php
$fiber = new Fiber(function (): void {
    echo "Fiber started.\n";
    Fiber::suspend('fiber paused');
    echo "Fiber resumed.\n";
});

$value = $fiber->start();
echo "Fiber suspended with value: " . $value . "\n";
$fiber->resume();
echo "Fiber finished.\n";
?>

Key Methods:

  • new Fiber(callable): Creates a new Fiber.
  • $fiber->start(): Starts the execution of the Fiber.
  • Fiber::suspend(): Pauses the execution of the Fiber and returns a value.
  • $fiber->resume(): Resumes the execution of the Fiber.
  • $fiber->isSuspended(): Checks if the Fiber is currently suspended.
  • $fiber->isTerminated(): Checks if the Fiber has terminated.

Use Cases

Fibers are particularly useful for building asynchronous tools and frameworks. They allow for writing asynchronous code that looks like synchronous, sequential code, making it easier to read and maintain. This is especially powerful for I/O-bound operations, like network requests or database queries, where the program would otherwise have to wait. Frameworks like Revolt and Amphp use Fibers to create asynchronous event loops.