CKTIS / PHP
Iteradores y generadores
iterable incluye arrays y objetos Traversable.
Versión: PHP 8.4; repository runtime, production runtime not attested
Sintaxis
function values(): Generator { yield 2; }iterable incluye arrays y objetos Traversable. Un generador produce bajo demanda y conserva su posición. Tras avanzar no siempre admite rebobinado y una vez cerrado no se recorre de nuevo. Otra llamada a la función crea un iterador independiente.
function values(){yield 2;yield 4;} $it=values();$first=iterator_to_array($it);
try{iterator_to_array($it);}catch(Exception $e){$closed=get_class($e);}echo json_encode([$first,$closed,iterator_to_array(values())]);
[[2,4],"Exception",[2,4]]
Ejemplos
<?php
function values(){yield 2;yield 4;} $it=values();$first=iterator_to_array($it);
try{iterator_to_array($it);}catch(Exception $e){$closed=get_class($e);}echo json_encode([$first,$closed,iterator_to_array(values())]);
Resultado
[[2,4],"Exception",[2,4]]