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 2The 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: helloFibers 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
EasyLet'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 aTaskRunnerclass that wraps fiber functionality for running tasks. The class should:- Have a private property to store a
Fiberinstance - 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(): boolthat returns whether the fiber has terminated
- Have a private property to store a
main.php— Include the TaskRunner file. You'll receive two inputs: a task name and a message to send to the fiber.Create a
TaskRunnerwith the given task name, then usecreateTask()to define a task that:- First suspends with the string
"Waiting for input" - Receives a value when resumed
- 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.- First suspends with the string
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 executionFiber::suspend($value)— pauses execution and returns a value to the callerresume($value)— continues execution and passes a value to the fiberisTerminated()— 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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System10Advanced OOP Concepts
Composition vs InheritanceDependency InjectionAnonymous ClassesEnums (PHP 8.1)Fibers (PHP 8.1)Object Cloning Deep DiveGenerators & Iterators2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern