Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / PHP

Parola chiave yield

Una funzione contenente yield restituisce un Generator senza eseguirne subito il corpo.

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

Sintassi

yield $key => $value;

Una funzione contenente yield restituisce un Generator senza eseguirne subito il corpo. A ogni yield espone chiave e valore e si sospende conservando lo stato locale. Avanzando riprende. Un return finale si legge separatamente con getReturn() dopo la conclusione normale. send($v) assegna $v al yield sospeso e riprende il generatore. Il chiamante riceve il successivo valore emesso e getReturn() dà poi il risultato finale separato.

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]

Esempi

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

Risultato

[[],{"a":2},["start","resume"],5]
["ready",10,6]

Fonti