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?
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.
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.
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.
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.
Your return type is Generator
, but you are using void
. Try the following:
public function getDataIncrementally(): \Generator {
yield from [/* some large set of numbers*/];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With