(yield 24); return 42; } $gen = gen2(); var_dump($gen->current()); $gen->next(); var_dump($gen->getReturn()); // & for generators specifies by-reference yield, not return // so it's okay to return a literal function &gen3() { $var = 24; (yield $var); return 42; } $gen = gen3(); var_dump($gen->current()); $gen->next(); var_dump($gen->getReturn()); // Return types for generators specify the return of the function, // not of the generator return value, so this code is okay function gen4() : Generator { (yield 24); return 42; } $gen = gen4(); var_dump($gen->current()); $gen->next(); var_dump($gen->getReturn()); // Has no explicit return, but implicitly return NULL at the end
<?php function gen3($start, $end) { $i = $start; while ($start < $end) { (yield $i++); } } $gen1 = gen3(0, 10); foreach ($gen1 as $value) { echo $value . "\n"; if ($value == 3) { $gen2 = clone $gen1; } } echo "Second generator: \n\n"; foreach ($gen2 as $value) { echo $value . "\n"; }
<?php function gen() { yield; return; } function gen2() { yield; return null; } function gen3() { return; yield; } function gen4() { return; yield; } var_dump(gen()); var_dump(gen2()); var_dump(gen3()); var_dump(gen4());
var_dump($gen->getReturn()); function gen2() { return "str"; // CONST yield; } $gen = gen2(); var_dump($gen->getReturn()); function gen3($var) { return $var; // CV yield; } $gen = gen3([1, 2, 3]); var_dump($gen->getReturn()); function gen4($obj) { return $obj->prop; // VAR yield; } $gen = gen4((object) ['prop' => 321]); var_dump($gen->getReturn()); function gen5($val) { return (int) $val; // TMP yield; }