0PricingLogin
PHP Academy · Lesson

PHP 8.1 Fibers

Pause and resume execution with native Fibers.

What Fibers Give You

PHP 8.1 added Fibers: a core primitive that lets you pause a running call stack and resume it later, from somewhere completely different. A Fiber is a full, independent stack you can suspend at an arbitrary point and continue without unwinding. This is the missing piece that lets libraries replace promise-chains with synchronous-looking await — the value behind ReactPHP and Amp's modern APIs.

Your First Fiber

Create a Fiber with a callback, start() it, and let it suspend() itself. Control returns to the caller at the suspension point; resume() continues from exactly there.

<?php
$fiber = new Fiber(function (): void {
    echo "A: inside fiber\n";
    $received = Fiber::suspend('paused');
    echo "C: resumed with '$received'\n";
});

$value = $fiber->start();          // prints A, returns 'paused'
echo "B: fiber suspended, got '$value'\n";
$fiber->resume('hello');           // prints C
echo "D: fiber done\n";

All lessons in this course

  1. The PHP Concurrency Model
  2. PHP 8.1 Fibers
  3. Event Loops with ReactPHP
  4. High-Performance Servers with Swoole
← Back to PHP Academy