Fibers (PHP 8.1)
| New Fiber | |
| Resume with values | |
| Suspend from inside | |
| Cooperative sketch |
New Fiber
A Fiber wraps a callable that can pause itself and continue later. Nothing runs at creation time, so start begins the first step on demand.
After start the Fiber either finishes or suspends, and the caller can inspect the state before moving on.
$fiber = new Fiber(function (): void { echo "inside"; }); $fiber->start(); var_dump($fiber->isTerminated());
Resume with values
Start and resume can pass values in both directions. The suspend call returns whatever the caller sends on the next resume.
The final return value comes back from start or from the last resume that lets the Fiber finish.
$fiber = new Fiber(function (): int { $v = Fiber::suspend("pause"); return strlen((string) $v); }); echo $fiber->start(); echo $fiber->resume("hello");
Suspend from inside
Only code inside the Fiber can suspend it. The pause returns control to whoever called start or resume last.
This rule keeps the flow explicit, since no outside code can freeze a Fiber at an arbitrary point.
$fiber = new Fiber(function (): void { echo "one"; Fiber::suspend(); echo "two"; }); $fiber->start(); $fiber->resume();
Cooperative sketch
Two Fibers can take turns by suspending after each small step. A tiny scheduler resumes each one in order until both are done.
This style suits tasks that wait often, because waiting time can be given to the next ready task.
$fiberA = new Fiber(function (): void { echo "A1"; Fiber::suspend(); echo "A2"; }); $fiberB = new Fiber(function (): void { echo "B1"; Fiber::suspend(); echo "B2"; }); $fiberA->start(); $fiberB->start(); $fiberA->resume(); $fiberB->resume();
Next: Attributes via reflection
Article author: Arthur Isaev