CKTIS / PHP
Generator
Chiamare una funzione generatrice crea un iteratore sospeso.
Versione: PHP 8.4; repository runtime, production runtime not attested
Sintassi
function sequence(): Generator { yield $value; }Chiamare una funzione generatrice crea un iteratore sospeso. Avanzando si riprende dopo yield. Il risultato di return è separato dagli elementi prodotti. getReturn funziona dopo il completamento normale e dà null se si raggiunge la fine del corpo. Prima della fine o dopo un’interruzione per eccezione lancia Exception. Un generatore esaurito in genere non può essere riavvolto e riusato. Dopo aver consumato entrambi i valori, Generator::getReturn legge il 5 del return del generatore.
function sequence(): Generator { yield "a"=>2; yield "b"=>3; return 5; }
$g=sequence(); $items=iterator_to_array($g); echo json_encode([$items,$g->getReturn(),$g->valid()]);
function aborted(): Generator { yield 1; throw new RuntimeException("stopped"); }
$bad=aborted(); try{$bad->getReturn();}catch(Exception $e){$early=get_class($e);} try{iterator_to_array($bad);}catch(RuntimeException $e){}
try{$bad->getReturn();}catch(Exception $e){$late=get_class($e);} echo PHP_EOL,json_encode([$early,$late]);
[{"a":2,"b":3},5,false]
["Exception","Exception"]
Esempi
<?php
function sequence(): Generator { yield "a"=>2; yield "b"=>3; return 5; }
$g=sequence(); $items=iterator_to_array($g); echo json_encode([$items,$g->getReturn(),$g->valid()]);
function aborted(): Generator { yield 1; throw new RuntimeException("stopped"); }
$bad=aborted(); try{$bad->getReturn();}catch(Exception $e){$early=get_class($e);} try{iterator_to_array($bad);}catch(RuntimeException $e){}
try{$bad->getReturn();}catch(Exception $e){$late=get_class($e);} echo PHP_EOL,json_encode([$early,$late]);
Risultato
[{"a":2,"b":3},5,false]
["Exception","Exception"]