Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP generator return type

I've never used generators in PHP before and there are no examples in the documentation that show the return type declaration.

In PhpStorm, there is an error in the IDE when I do this:

public function getDataIncrementally(): void {
    yield from [/* some large set of numbers*/];
}

The error is:

Generators may only declare a return type of Generator, Iterator or Traversable, or iterable, void is not permitted.

I can see the inheritance tree is Traversable -> Iterator -> Generator. Meanwhile, iterable is a new pseudo-type introduced in PHP 7.1.

Would it be appropriate to use iterable for the return type declaration if I only need to support PHP >= 7.1?

like image 576
rink.attendant.6 Avatar asked Feb 09 '19 06:02

rink.attendant.6


People also ask

What is a generator function PHP?

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.

What is yield PHP?

Definition and Usage The yield keyword is used to create a generator function. Generator functions act as iterators which can be looped through with a foreach loop. The value given by the yield keyword is used as a value in one of the iterations of the loop.

What is an iterable in PHP?

An iterable is any value which can be looped through with a foreach() loop. The iterable pseudo-type was introduced in PHP 7.1, and it can be used as a data type for function arguments and function return values.

What is a generator and how is it used in PHP Linkedin?

Generators are simple iterators. In other words, they can be used inside a loop to generate multiple values. Because they use the same syntax as functions, there's no need to define a class.


1 Answers

Your return type is Generator, but you are using void. Try the following:

public function getDataIncrementally(): \Generator {
    yield from [/* some large set of numbers*/];
}
like image 53
Petro Chaikivskyi Avatar answered Oct 18 '22 17:10

Petro Chaikivskyi