← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 16 of 24

PHP Fibers

What are Fibers?

Fibers, added in PHP 8.1, are lightweight cooperative coroutines that let a function pause partway through and later resume exactly where it left off, useful for building async-style code without threads.

Example: What are Fibers?

php
<?php
// PHP 8.1+
$fiber = new Fiber(function () {
    echo "Fiber started\n";
});
echo get_class($fiber);
?>

Creating and Starting a Fiber

Creating a Fiber wraps a block of code in a closure passed to new Fiber(); nothing runs until you explicitly call start(), which begins executing that closure until it suspends or finishes.

Example: Creating and Starting a Fiber

php
<?php
$fiber = new Fiber(function () {
    echo "Running inside the fiber\n";
});
$fiber->start();
?>

Suspending Execution

Calling the static Fiber::suspend() from inside the running closure pauses execution at that exact point and hands control back to whatever code started or resumed the fiber.

Example: Suspending Execution

php
<?php
$fiber = new Fiber(function () {
    echo "Before suspend\n";
    Fiber::suspend();
    echo "After resume\n";
});
$fiber->start();
echo "Back in main code\n";
?>

Resuming Execution

resume() picks a suspended fiber back up exactly where suspend() paused it, optionally passing a value back into the paused code -- this back-and-forth is what enables cooperative scheduling.

Example: Resuming Execution

php
<?php
$fiber = new Fiber(function () {
    $value = Fiber::suspend('paused');
    echo "Resumed with: $value\n";
});
$fiber->start();
$fiber->resume('hello');
?>

Checking Fiber States

isStarted(), isSuspended(), and isTerminated() let you check a fiber's current state before acting on it, preventing errors like trying to resume a fiber that has already finished.

Example: Checking Fiber States

php
<?php
$fiber = new Fiber(function () {
    Fiber::suspend();
});
var_dump($fiber->isStarted());
$fiber->start();
var_dump($fiber->isSuspended());
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.