CKTIS / PHP
Palavra-chave yield
Uma função com yield devolve um Generator sem executar logo o corpo.
Versão: PHP 8.4; repository runtime, production runtime not attested
Sintaxe
yield $key => $value;Uma função com yield devolve um Generator sem executar logo o corpo. Cada yield expõe chave e valor e suspende preservando o estado local. Avançar retoma a execução. O return final lê-se separadamente com getReturn() depois da conclusão normal. send($v) dá $v ao yield suspenso e retoma o gerador. O chamador recebe o próximo valor emitido e getReturn() dá depois o resultado final separado.
function stream(&$trace){$trace[]="start"; yield "a"=>2; $trace[]="resume"; return 5;}
$t=[]; $g=stream($t); $initial=$t; $values=iterator_to_array($g); echo json_encode([$initial,$values,$t,$g->getReturn()]);
function channel(){ $n=yield "ready"; yield $n*2; return $n+1; } $ch=channel(); $start=$ch->current(); $sent=$ch->send(5); $ch->next(); echo "\n",json_encode([$start,$sent,$ch->getReturn()]);
[[],{"a":2},["start","resume"],5]
["ready",10,6]
Exemplos
<?php
function stream(&$trace){$trace[]="start"; yield "a"=>2; $trace[]="resume"; return 5;}
$t=[]; $g=stream($t); $initial=$t; $values=iterator_to_array($g); echo json_encode([$initial,$values,$t,$g->getReturn()]);
function channel(){ $n=yield "ready"; yield $n*2; return $n+1; } $ch=channel(); $start=$ch->current(); $sent=$ch->send(5); $ch->next(); echo "\n",json_encode([$start,$sent,$ch->getReturn()]);
Resultado
[[],{"a":2},["start","resume"],5]
["ready",10,6]