Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

Generator

Llamar a una función generadora crea un iterador suspendido.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

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

Llamar a una función generadora crea un iterador suspendido. Avanzar reanuda la ejecución tras yield. El resultado de return es independiente de los elementos emitidos. getReturn funciona tras terminar normalmente y da null al alcanzar el final del cuerpo. Antes del final o tras abortar por una excepción lanza Exception. Un generador agotado normalmente no se puede rebobinar y reutilizar. Tras consumir ambos valores, Generator::getReturn lee el 5 del return del generador.

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

Ejemplos

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

Resultado

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

Fuentes