Menu
Coddy logo textTech

Fibers (PHP 8.1)

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 60 of 91.

Fibers are a PHP 8.1 feature that enables interruptible code execution. Unlike regular functions that run from start to finish, a fiber can pause itself mid-execution and resume later, maintaining its state between pauses.

Create a fiber by passing a callable to the Fiber class, then start it with start():

<?php
$fiber = new Fiber(function(): void {
    echo "Step 1\n";
    Fiber::suspend();
    echo "Step 2\n";
});

$fiber->start();
echo "Between steps\n";
$fiber->resume();

Output:

Step 1
Between steps
Step 2

The fiber runs until it hits Fiber::suspend(), then control returns to the main code. Calling resume() continues execution from where it paused.

Fibers can also pass values when suspending and resuming:

<?php
$fiber = new Fiber(function(): string {
    $value = Fiber::suspend("paused");
    return "Received: $value";
});

$suspended = $fiber->start();
echo "$suspended\n";

$result = $fiber->resume("hello");
echo $result;

Output:

paused
Received: hello

Fibers are the foundation for asynchronous PHP frameworks. While you won't use them directly in most applications, understanding them helps when working with async libraries that handle concurrent operations like HTTP requests or database queries without blocking.

challenge icon

Challenge

Easy

Let's build a task scheduler that demonstrates how fibers can pause and resume execution while passing data between the fiber and the main code. You'll create a system where tasks can be interrupted, allowing other work to happen in between.

You'll organize your code across two files:

  • TaskRunner.php — Create a TaskRunner class that wraps fiber functionality for running tasks. The class should:
    • Have a private property to store a Fiber instance
    • Accept a task name (string) in its constructor using constructor promotion
    • Have a method createTask(callable $task) that creates a new Fiber with the given callable and stores it
    • Have a method start() that starts the fiber and returns whatever value the fiber suspends with (or the final return value)
    • Have a method continue(mixed $value) that resumes the fiber with the given value and returns the next suspended value (or final return value)
    • Have a method isFinished(): bool that returns whether the fiber has terminated
  • main.php — Include the TaskRunner file. You'll receive two inputs: a task name and a message to send to the fiber.

    Create a TaskRunner with the given task name, then use createTask() to define a task that:

    1. First suspends with the string "Waiting for input"
    2. Receives a value when resumed
    3. Returns "Completed: [received value]"

    Start the task and print what it returns when it first suspends. Then print "Processing..." to show work happening between fiber pauses. Finally, continue the fiber by passing in the message input, and print the final result.

This challenge shows how fibers enable cooperative multitasking — your task pauses itself at a convenient point, the main code does other work, then resumes the task with new data. The fiber maintains its state throughout, picking up exactly where it left off.

Cheat sheet

Fibers enable interruptible code execution in PHP 8.1+. Unlike regular functions, a fiber can pause mid-execution and resume later while maintaining its state.

Create a fiber by passing a callable to the Fiber class and start it with start():

<?php
$fiber = new Fiber(function(): void {
    echo "Step 1\n";
    Fiber::suspend();
    echo "Step 2\n";
});

$fiber->start();
echo "Between steps\n";
$fiber->resume();

The fiber runs until Fiber::suspend(), then control returns to the main code. Call resume() to continue execution from where it paused.

Fibers can pass values when suspending and resuming:

<?php
$fiber = new Fiber(function(): string {
    $value = Fiber::suspend("paused");
    return "Received: $value";
});

$suspended = $fiber->start();
$result = $fiber->resume("hello");

Key methods:

  • start() — begins fiber execution
  • Fiber::suspend($value) — pauses execution and returns a value to the caller
  • resume($value) — continues execution and passes a value to the fiber
  • isTerminated() — checks if the fiber has finished

Try it yourself

<?php

require_once 'TaskRunner.php';

// Read inputs
$taskName = trim(fgets(STDIN));
$message = trim(fgets(STDIN));

// TODO: Create a TaskRunner with the given task name

// TODO: Use createTask() to define a task that:
// 1. First suspends with the string "Waiting for input"
// 2. Receives a value when resumed
// 3. Returns "Completed: [received value]"

// TODO: Start the task and print what it returns when it first suspends

// TODO: Print "Processing..." to show work happening between fiber pauses

// TODO: Continue the fiber by passing in the message input

// TODO: Print the final result

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming