Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does php return an empty Generator if function contains both return and yield?

// Returns empty generator as expected.
function yieldOnly(): Generator
{
    yield;
}

// Throws TypeError as expected.
function returnOnly(): Generator
{
    return;
}

// Returns empty generator???
function returnAndYield(): Generator
{
    return;
    yield;
}

The return value of returnAndYield() is an empty Generator, although I was expecting it to throw a TypeError. Is this the expected behavior? I could not find it documented anywhere and am wondering if this is potentially a bug that should be reported.

like image 785
Leo Galleguillos Avatar asked Oct 18 '25 14:10

Leo Galleguillos


1 Answers

The manual about the generator syntax says the following:

Any function containing yield is a generator function.

So by having the yield keyword in there results in having a generator function. With the return keyword you are quitting the function, which is used to build a generator function. In this case it's just empty because before the return statement are no yield lines. When you use the following source code:

function returnAndYield(): Generator
{
    yield 1;
    yield 2;
    return;
    yield 3;
    yield 4;
}

$result = returnAndYield();
echo implode(',', iterator_to_array($result));

you will get the following output:

1,2

The values 3 and 4 are not in the generator because the function exits before these yield statements.

like image 62
Progman Avatar answered Oct 20 '25 05:10

Progman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!