Fibers

A Fiber lets a piece of code pause itself partway through and hand control back to whoever started it, then continue later from exactly the same spot, with all its local variables intact. This is different from a normal function call, which always runs start-to-finish in one go. Create a fiber with new Fiber($callback), then call ->start() to begin running $callback (any arguments passed to start() are forwarded to it).

<?php
$fiber = new Fiber(function () {
  echo "Fiber started\n";
  $value = Fiber::suspend('first suspend');
  echo "Fiber resumed with: $value\n";
  $value = Fiber::suspend('second suspend');
  echo "Fiber resumed with: $value\n";
  return 'fiber return value';
});

$value = $fiber->start();
echo "Got from fiber: $value\n";

$value = $fiber->resume('hello');
echo "Got from fiber: $value\n";

$fiber->resume('world');
echo "Fiber finished, return value: " . $fiber->getReturn() . "\n";
?>

Fiber started Got from fiber: first suspend Fiber resumed with: hello Got from fiber: second suspend Fiber resumed with: world Fiber finished, return value: fiber return value
Inside the fiber, Fiber::suspend($value) pauses execution right there and passes $value back out to whichever call — start() or resume() — is currently running the fiber. The caller then resumes it with ->resume($value), and that $value becomes the result of the paused Fiber::suspend() expression inside the fiber, so execution continues right after it. Once the fiber's callback finally returns, ->getReturn() retrieves its return value; calling getReturn() before the fiber has finished throws a \FiberError instead.