Early return in functions and yield

Viewed 223

I'm not sure what the correct way is to early return in a function when using the yield keyword.

Is a "return void" return; the correct return value? Because the return type is specified to be iterable. Although it works without any error, returning void if the type hint would be int would lead to an error. So is iterable type hint an exception to still accept a void return statement although the type hint indicates something iterable should be returned?

See the example below to clarify my question:

class Collection
{
    public $items;
}

class OrderedCollection extends Collection
{
    public $orderedItems;
}

class Test
{
    public function getCollectionItems(Collection $collection): iterable
    {
        if ($collection instanceof OrderedCollection) {
            yield from $collection->orderedItems;
            return; // What should I return here to early exit the function?
        }

        yield from $collection->items;
    }
}
0 Answers
Related