CKTIS / PHP
Iteradores e geradores
iterable abrange arrays e objetos Traversable.
Versão: PHP 8.4; repository runtime, production runtime not attested
Sintaxe
function values(): Generator { yield 2; }iterable abrange arrays e objetos Traversable. Um gerador produz a pedido e guarda a posição. Depois de avançar nem sempre permite rebobinar e depois de fechar não se percorre de novo. Outra chamada à função cria um iterador independente.
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]]
Exemplos
<?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]]