...

/

Learning About PHP 8.1 Fibers

Learning About PHP 8.1 Fibers

Learn about fibers in PHP 8, including how to use them effectively in PHP 8 applications.

A Request for Comments (RFC) was published in March 2021 by Aaron Piotrowski and Niklas Keller, both PHP core team developers, outlining the case for including support for fibers in the PHP language core. The RFC was ratified at the end of the month and has now been implemented in the upcoming 8.1 version of PHP.

The fiber implementation is low-level, meaning that it is mainly designed to be used as part of a PHP async framework such as ReactPHP or Amp or an extension such as the Swoole extension. Because this will, as of PHP 8.1 and beyond, be a core part of the language, developers will not have to worry so much about which extensions are loaded. Also, this greatly enhances PHP async frameworks as they now have low-level support directly in the language core, greatly improving performance. Let’s now have a look at the Fiber class itself.

Discovering the Fiber class

The PHP 8.1 Fiber class offers a bare-bones implementation upon which async framework and extension developers can build timers, event loops, promises, and other async artifacts.

Here is the formal class definition:

final class Fiber {
public function __construct(callable $callback) {}
public function start(mixed ...$args): mixed {}
public function resume(mixed $value = null): mixed {}
public function throw(Throwable $exception): mixed {}
public function isStarted(): bool {}
public function isSuspended(): bool {}
public function isRunning(): bool {}
public function isTerminated(): bool {}
public function getReturn(): mixed {}
public static function this(): ?self {}
public static function suspend(
mixed $value = null): mixed {}
}
Implementation of the Fiber class

Here is a summary of the Fiber class methods:

Summary of Each Fiber Class Method

Fiber class method 

Description

Fiber::start()

Starts fiber execution. The callback associated with the fiber can then be suspended, canceled, and resumed at will. Any arguments are passed to the callback. Suspend the fiber by making a static call $fiber::suspend(). Cancel the fiber by having it throw an exception using $fiber->throw(). Restarts fiber execution.

Fiber::resume()

Returns the value provided by Fiber::suspend().

Fiber::suspend()

This method is made via a static call from inside the callback assigned to the fiber. We can then resume or cancel the fiber using suspend() or throw().

Fiber::throw()

When calling this method, provide an instance of Throwable. The fiber is then canceled.

Fiber::isStarted()

Fiber::isSuspended()

Fiber::isRunning()

Fiber::isTerminated()

These four methods return a boolean and are used to display the state of the fiber.

Fiber::getReturn()

Much like a PHP Generator, we can use this method to get the value provided by the callback's return (if any).

Fiber::this()

Returns the currently running fiber instance.

...