Fibers let a PHP callable suspend and resume execution cooperatively.
The examples focus on the operation itself, including the important distinction: Generators yield values during iteration; Fibers suspend execution at arbitrary points.
What It Does
Use the examples below to observe the behavior on a small dataset before extending it to application code.
Before You Start
Read the input requirements before applying this pattern to production data.
Example 1: Basic Use
A Fiber suspends cooperatively; the application must call resume itself.
<?php
$fiber = new Fiber(static function (): string {
$payload = Fiber::suspend("waiting");
return "resumed:" . $payload;
});
$first = $fiber->start();
$fiber->resume('new');
echo $first . " / " . $fiber->getReturn();
Output from a successful local PHP 8.4 run:
waiting / resumed:new
Example 2: Checking Behavior
A Fiber suspends cooperatively; the application must call resume itself.
<?php
$fiber = new Fiber(static function (): string {
$payload = Fiber::suspend("waiting");
return "resumed:" . $payload;
});
$first = $fiber->start();
$fiber->resume('ready');
echo $first . " / " . $fiber->getReturn();
Output from a successful local PHP 8.4 run:
waiting / resumed:ready
Example 3: Practical Example
A Fiber suspends cooperatively; the application must call resume itself.
<?php
$fiber = new Fiber(static function (): string {
$payload = Fiber::suspend("waiting");
return "resumed:" . $payload;
});
$first = $fiber->start();
$fiber->resume('done');
echo $first . " / " . $fiber->getReturn();
Output from a successful local PHP 8.4 run:
waiting / resumed:done
Important Behavior and Edge Cases
Fibers do not independently schedule I/O or provide threads; a scheduler is required for useful concurrency.
Comparison with Related Approaches
| Approach | Difference |
|---|---|
| Using Fibers for Async-Like Workflows | Fibers let a PHP callable suspend and resume execution cooperatively. |
| Related API or alternative | Generators yield values during iteration; Fibers suspend execution at arbitrary points. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the operation-specific limits | Fibers do not independently schedule I/O or provide threads; a scheduler is required for useful concurrency. |
| Confusing it with a related API | Generators yield values during iteration; Fibers suspend execution at arbitrary points. |
Key Takeaways
- Fibers let a PHP callable suspend and resume execution cooperatively.
- Fibers do not independently schedule I/O or provide threads; a scheduler is required for useful concurrency.
- Generators yield values during iteration; Fibers suspend execution at arbitrary points.
Use Using Fibers for Async-Like Workflows when its documented behavior matches the problem. Test the relevant edge cases in your own runtime before deploying it.