Cannot Return Value from Generator

Fatal error: Generators cannot return values using "return" in PHP 5.x

Quick Answer

In PHP versions before 7.0, generators cannot use return with a value. Either upgrade to PHP 7+ or yield the final value instead.

Why This Happens

PHP 5.x generators could only use return without a value. PHP 7.0 added support for return values in generators accessible via Generator::getReturn(). If you are on PHP 7+, you can return values but must call getReturn() on the generator to retrieve them.

The Problem

function fibonacci(): Generator {
    $a = 0;
    $b = 1;
    while (true) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}
$gen = fibonacci();
$gen->next();
echo $gen->return; // Wrong way to get return value

The Fix

function fibonacci(int $limit): Generator {
    $a = 0;
    $b = 1;
    $count = 0;
    while ($count < $limit) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
        $count++;
    }
    return $count; // PHP 7+ supports this
}
$gen = fibonacci(10);
foreach ($gen as $num) {
    echo $num . ' ';
}
echo 'Generated: ' . $gen->getReturn(); // Use getReturn()

Step-by-Step Fix

  1. 1

    Check your PHP version

    Run php -v to see your version. Generator return values require PHP 7.0 or later.

  2. 2

    Use getReturn correctly

    After the generator is fully consumed, call $generator->getReturn() to retrieve the return value.

  3. 3

    Upgrade if needed

    If on PHP 5.x, either upgrade PHP or yield the final value and track it externally.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free