Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword yield

A function containing yield returns a Generator without running its body immediately.

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

Syntax

yield $key => $value;

A function containing yield returns a Generator without running its body immediately. At each yield it exposes a key and value and suspends while retaining local state. Advancing resumes after that point. A final return is separate from yielded values and can be read with getReturn() after normal completion. send($v) makes $v the value of the suspended yield expression and resumes execution. Its caller receives the next yielded value. getReturn() separately retrieves the final result.

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]

Examples

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

Result

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

Sources