CKTIS / PHP
Fiber
Sospende e riprende un contesto cooperativo da PHP 8.1. start restituisce l’argomento di suspend e l’argomento di resume diventa il risultato interno di suspend.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
new Fiber($callback)Sospende e riprende un contesto cooperativo da PHP 8.1. start restituisce l’argomento di suspend e l’argomento di resume diventa il risultato interno di suspend. Dopo il completamento getReturn dà il risultato della funzione. La fibra non si pianifica da sola. Senza sospensione start restituisce null. Un’eccezione della funzione si propaga al chiamante e getReturn lancia FiberError dopo tale arresto.
$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"]
Esempi
<?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]);
Risultato
["ready",true,null,true,6] [null,3,"LogicException","FiberError"]