PHP Fibers
In this page:
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 8.1+
$fiber = new Fiber(function () {
echo "Fiber started\n";
});
echo get_class($fiber);
?>
Login to try C/C++/Java/PHP code in the editor
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
$fiber = new Fiber(function () {
echo "Running inside the fiber\n";
});
$fiber->start();
?>
Login to try C/C++/Java/PHP code in the editor
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
$fiber = new Fiber(function () {
echo "Before suspend\n";
Fiber::suspend();
echo "After resume\n";
});
$fiber->start();
echo "Back in main code\n";
?>
Login to try C/C++/Java/PHP code in the editor
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
$fiber = new Fiber(function () {
$value = Fiber::suspend('paused');
echo "Resumed with: $value\n";
});
$fiber->start();
$fiber->resume('hello');
?>
Login to try C/C++/Java/PHP code in the editor
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
$fiber = new Fiber(function () {
Fiber::suspend();
});
var_dump($fiber->isStarted());
$fiber->start();
var_dump($fiber->isSuspended());
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser