Mastering PHP 8.1 Fibers: Theory, API, and Practical Examples
This article explains PHP 8.1 Fibers, covering their conceptual model, the final \Fiber class API, exception handling, and real‑world code samples such as a simple echo program and a file‑copy utility with progress reporting.
Fiber Overview
PHP 8.1 introduced Fibers, a low‑level feature that enables cooperative multitasking by allowing a function to pause and later resume execution from any point in the call stack. Fibers are created, started, suspended, and terminated entirely by user code.
Difference from Threads and Generators
Threads are scheduled by the operating system and have nondeterministic pause/resume points. Generators (added in PHP 5.4) can yield values but cannot be resumed from the exact yield point. Fibers retain state like generators and provide precise, program‑controlled suspension and resumption.
Fiber Class
The final Fiber class cannot be extended. Its public API:
__construct(callable $callback)
start(mixed ...$args): mixed
resume(mixed $value = null): mixed
throw(Throwable $exception): mixed
getReturn(): mixed
isStarted(): bool
isSuspended(): bool
isRunning(): bool
isTerminated(): bool
static suspend(mixed $value = null): mixed
static getCurrent(): ?Fiber
Creating a Fiber
new Fiber('var_dump');
new Fiber(fn(string $msg) => print $msg);
new Fiber(function(string $msg): void {
print $msg;
});Starting a Fiber
$fiber = new Fiber(fn(string $msg) => print $msg);
$fiber->start('Hi'); // outputs HiSuspending and Resuming
Fiber::suspend()is a static method that can only be called from inside a running Fiber. It optionally returns a value to the caller of start() or resume(). Calling it outside a Fiber throws FiberError.
$fiber = new Fiber(function() {
Fiber::suspend(42);
});
$return = $fiber->start(); // $return is 42Resuming passes an optional value back into the Fiber, becoming the result of the preceding suspend() call.
$fiber = new Fiber(function() {
$last = Fiber::suspend(16);
echo "Resuming with last value {$last}
";
});
$last = $fiber->start(); // $last = 16
$fiber->resume(42); // prints "Resuming with last value 42"State Inspection
isStarted()– true after start() has been called. isSuspended() – true while the Fiber is paused. isRunning() – true only during active execution. isTerminated() – true after the callback finishes.
Exceptions
Two internal throwable classes are introduced in PHP 8.1 and cannot be instantiated directly: FiberError – thrown for invalid actions such as resuming a terminated Fiber. FiberExit – thrown when a Fiber is destroyed; it cannot be caught by user code.
Practical Examples
Simple Echo Program
$fiber = new Fiber(function(): void {
echo "Hello from the Fiber...
";
Fiber::suspend();
echo "Hello again from the Fiber...
";
});
echo "Starting the program...
";
$fiber->start();
echo "Taken control back...
";
$fiber->resume();
echo "Program exits...
";File‑Copy with Progress Bar
function writeToLog(string $msg): void {
echo $msg . "
";
}
$files = [
'src/foo.png' => 'dest/foo.png',
'src/bar.png' => 'dest/bar.png',
'src/baz.png' => 'dest/baz.png',
];
$fiber = new Fiber(function(array $files): void {
foreach ($files as $source => $destination) {
copy($source, $destination);
Fiber::suspend([$source, $destination]);
}
});
$copied = $fiber->start($files);
$copiedCount = 1;
$totalCount = count($files);
while (!$fiber->isTerminated()) {
$percentage = round($copiedCount / $totalCount, 2) * 100;
writeToLog("[{$percentage}%]: Copied '{$copied[0]}' to '{$copied[1]}'");
$copied = $fiber->resume();
++$copiedCount;
}
writeToLog('Completed');Image
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
