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

CKTIS / PHP

Palabra clave yield

Una función con yield devuelve un Generator sin ejecutar el cuerpo de inmediato.

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

Sintaxis

yield $key => $value;

Una función con yield devuelve un Generator sin ejecutar el cuerpo de inmediato. Cada yield expone clave y valor y suspende conservando el estado local. Avanzar reanuda la ejecución. El return final se consulta aparte con getReturn() tras la terminación normal. send($v) da $v al yield suspendido y reanuda el generador. El llamante recibe el siguiente valor emitido y getReturn() da después el 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]

Ejemplos

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

Fuentes