CKTIS / PHP
Generator::getReturn — read a generator’s return value
Read a generator’s final result after it completes normally. The value from `return` is separate from the items produced by `yield`.
Version: PHP 8.3
Syntax
public function Generator::getReturn(): mixedGenerator::getReturn is a public instance method on the built-in \Generator class, available since PHP 7.0. It requires no optional extension. Call it with no arguments as $generator->getReturn(). Calling a generator function gives you a \Generator object; the mixed return type in the PHP 8.3 signature shown here describes the generator’s final value, not the type of that object.
yield supplies an item to the iteration and pauses execution. return ends the generator, and its value does not become another foreach item. After the loop runs to completion, read the result from the same object. Receiving the last item is not enough: a break can leave the generator paused at yield, and calling the method in that state throws \Exception.
If the generator finishes normally without returning a value, the method returns null. If an uncaught exception terminates the generator, there is no result to read, and a later call to getReturn() throws \Exception. When delegating to another generator, yield from forwards its items and evaluates to its final value. The outer generator can return that value as its own with return yield from $inner;.
Examples
<?php
function readings(): \Generator
{
$total = 0;
foreach ([4, 7] as $reading) {
$total += $reading;
yield $reading;
}
return $total;
}
$generator = readings();
foreach ($generator as $reading) {
echo 'item: ', $reading, "\n";
}
echo 'total: ', $generator->getReturn(), "\n";
Result
item: 4 item: 7 total: 11
`foreach` prints the readings `4` and `7`. Only after the loop does `getReturn()` expose the total `11`, which is not an iteration item.
Related lessons
- PHP · Lesson 59 · Advanced · Version: 2