Generators Flashcards
How are generators useful?
They provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.
What does a generator do?
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 (this saves you from exceeding a memory limit, or requiring a considerable amount of processing time to generate).
What’s the difference between a generator and a normal function?
Instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.
What does a generator function return?
An object that can be iterated over.
What happens when you iterate over a generator object?
PHP will call the generator function each time it needs a value, then saves the state of the generator when the generator yields a value so that it can be resumed when the next value is required.
Can a generator return a value?
No. Doing so will result in a compile error.
Is an empty return statement valid syntax within a generator?
Yes. It will terminate the generator.
What’s the difference between yield and return?
Return stops execution of a function and returns. Yield provides a value to the code looping over the generator and pauses execution of the generator function.
If you use yield in an expression context (for example, on the right hand side of an assignment), you must…
…surround the yield statement with parentheses. For example, this is valid:
$data = (yield $value);
But this is not:
$data = yield $value;
This syntax may be used in conjunction with the Generator::send() method.
Do yield statements work with associative arrays?
Yes. In addition to yielding simple values, you can also yield a key at the same time.
Yielding a key/value pair in an expression context requires…
…the yield statement to be parenthesised.
$data = (yield $key => $value);
What happens when yield is called without an argument?
It yields a NULL value with an automatic key.
Can generators yield values by reference?
Yes. It’s done in the same way as returning references from functions: by prepending an ampersand to the function name.
What is returned when a generator function is called for the first time?
An object of the internal Generator class. This object implements the Iterator interface in much the same way as a forward-only iterator object would.
How are generators superior to implementing an Iterator class?
Much less boilerplate code has to be written, and the code is generally much more readable.