Member-only story
A Look at the New PHP 8.1 Fibers Feature
Understand how it works and what it means for concurrency’s future in PHP
PHP is trying to shove the lack of features from its code base, and Fibers is one of the meaningful additions to the language. PHP Fibers, incoming in PHP 8.1 at the end of the year, will introduce a sort of async programming (coroutines) into the wild.
The fiber concept basically refers to a lightweight thread of execution (also called coroutine). These seem to run in parallel but are ultimately handled by the runtime itself rather than by pushing it directly to the CPU. A lot of major languages have their own ways to implement them, but the principle is the same: Let the computer do two or more things at the same time, and wait until everything is completed.
PHP implementation of Fibers is not true asynchronous computing, as one may think. Indeed, the core of PHP will be still synchronous after Fibers are introduced.
You can think of PHP Fibers as being like switching from one car to another.
How Will Fibers Work?
A Fiber is a single final class that looks like a car: It can start and run immediately, push the brakes and wait, and resume its trip.
When you create a new Fiber instance with a callable
, nothing will happen. Is not until you start the Fiber that the callback is executed like any other normal PHP code.
$fiber = new Fiber(function() : void {
echo "I'm running a Fiber, yay!";
});$fiber->start(); // I'm running a Fiber, yay!
Didn’t I say Fibers were asynchronous? They are, but only until you hit the brakes by calling Fiber::suspend()
inside the callback. Then it passes the control to the “outside,” but bear in mind this Fiber car is still alive and waiting to resume.
$fiber = new Fiber(function() : void {
Fiber::suspend();
echo "I'm running a Fiber, yay!";
});