Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Generator

Calling a generator function creates a suspended iterator.

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

Syntax

function sequence(): Generator { yield $value; }

Calling a generator function creates a suspended iterator. Execution resumes at yield as consumers advance it. A returned value is separate from the yielded elements. getReturn succeeds only after normal completion, with null for falling off the end. Before completion or after termination by an exception it throws Exception. An exhausted generator cannot generally be rewound and reused. After both yielded values have been consumed, Generator::getReturn reads the 5 from the generator’s return statement.

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"]

Examples

<?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]);

Result

[{"a":2,"b":3},5,false]
["Exception","Exception"]

Sources