0
0
PHPprogramming~7 mins

Fibers for concurrency in PHP

Choose your learning style9 modes available
Introduction

Fibers let you pause and resume parts of your program. This helps run multiple tasks smoothly without waiting for each to finish.

When you want to run several tasks that wait for something, like reading files or network calls.
When you want to keep your program responsive while doing slow work.
When you want to write code that looks simple but runs tasks one after another without blocking.
When you want to manage multiple small jobs inside one program without using heavy threads.
Syntax
PHP
<?php
$fiber = new Fiber(function(): void {
    // code to run inside the fiber
    $value = Fiber::suspend('pause');
    echo "Resumed with value: $value\n";
});

// Start the fiber
$result = $fiber->start();
echo "Fiber suspended with: $result\n";

// Resume the fiber
$fiber->resume('hello');

Create a Fiber with new Fiber(function() { ... }).

Use Fiber::suspend() to pause and send a value outside.

Examples
Simple fiber that just prints a message.
PHP
<?php
$fiber = new Fiber(function() {
    echo "Inside fiber\n";
});
$fiber->start();
Fiber suspends and sends 'waiting', then resumes with 'done'.
PHP
<?php
$fiber = new Fiber(function() {
    $value = Fiber::suspend('waiting');
    echo "Got: $value\n";
});

$result = $fiber->start();
echo "Suspended with: $result\n";
$fiber->resume('done');
Sample Program

This program shows how a fiber pauses and resumes multiple times, exchanging data with the main program.

PHP
<?php
$fiber = new Fiber(function(): void {
    echo "Step 1: Start\n";
    $value = Fiber::suspend('paused at step 1');
    echo "Step 2: Resumed with $value\n";
    $value = Fiber::suspend('paused at step 2');
    echo "Step 3: Resumed with $value\n";
});

// Start fiber and get first suspend value
$suspendValue = $fiber->start();
echo "Main received: $suspendValue\n";

// Resume fiber with a value
$suspendValue = $fiber->resume('data for step 2');
echo "Main received: $suspendValue\n";

// Resume fiber again
$fiber->resume('data for step 3');
OutputSuccess
Important Notes

Fibers are not threads; they run in the same thread but can pause and resume.

Use fibers to write asynchronous code in a simple, step-by-step style.

Summary

Fibers let you pause and resume code blocks to handle tasks smoothly.

You create fibers with new Fiber() and control them with start() and resume().

Fibers help keep programs responsive without complex threading.