Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Fiber

Suspend and resume a cooperative execution context, available since PHP 8.1. start returns the value given to suspend, while the next resume argument becomes the result of suspend inside the fiber.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new Fiber($callback)

Suspend and resume a cooperative execution context, available since PHP 8.1. start returns the value given to suspend, while the next resume argument becomes the result of suspend inside the fiber. Once the callback finishes, getReturn retrieves its return value. Fibers do not schedule themselves. Without suspension start returns null. A callback exception propagates to the caller, and getReturn after that failure throws FiberError.

$fiber=new Fiber(function(): int {$n=Fiber::suspend("ready"); return $n*2;});
$first=$fiber->start(); $paused=$fiber->isSuspended(); $last=$fiber->resume(3);
echo json_encode([$first,$paused,$last,$fiber->isTerminated(),$fiber->getReturn()]);
$plain=new Fiber(fn()=>3); $started=$plain->start();
$bad=new Fiber(fn()=>throw new LogicException("halt")); try{$bad->start();}catch(LogicException $e){$propagated=get_class($e);}
try{$bad->getReturn();}catch(FiberError $e){$noResult=get_class($e);} echo PHP_EOL,json_encode([$started,$plain->getReturn(),$propagated,$noResult]);
["ready",true,null,true,6]
[null,3,"LogicException","FiberError"]

Examples

<?php
$fiber=new Fiber(function(): int {$n=Fiber::suspend("ready"); return $n*2;});
$first=$fiber->start(); $paused=$fiber->isSuspended(); $last=$fiber->resume(3);
echo json_encode([$first,$paused,$last,$fiber->isTerminated(),$fiber->getReturn()]);
$plain=new Fiber(fn()=>3); $started=$plain->start();
$bad=new Fiber(fn()=>throw new LogicException("halt")); try{$bad->start();}catch(LogicException $e){$propagated=get_class($e);}
try{$bad->getReturn();}catch(FiberError $e){$noResult=get_class($e);} echo PHP_EOL,json_encode([$started,$plain->getReturn(),$propagated,$noResult]);

Result

["ready",true,null,true,6]
[null,3,"LogicException","FiberError"]

Sources