Consider the following PHP code using a generator with a return value. What will be the output?
<?php function gen() { yield 1; yield 2; return 3; } $generator = gen(); foreach ($generator as $value) { echo $value . ' '; } echo $generator->getReturn();
Remember that yield produces values one by one, and return sets the generator's return value accessible by getReturn().
The foreach loop outputs the yielded values 1 and 2. After the loop ends, getReturn() returns the value passed by return, which is 3. So the output is 1 2 3.
What is the value returned by getReturn() after iterating this generator?
<?php function numbers() { yield 10; yield 20; return 42; } $gen = numbers(); foreach ($gen as $num) { // just iterate } echo $gen->getReturn();
The return statement in a generator sets the return value accessible by getReturn().
After the generator finishes yielding values, getReturn() returns the value given by return, which is 42.
Examine the code below. Why does calling getReturn() cause a fatal error?
<?php function gen() { yield 1; return 5; } $g = gen(); echo $g->getReturn();
Think about when the generator finishes execution and when the return value is available.
The getReturn() method can only be called after the generator has finished. Since the generator was not iterated, it is not finished, so calling getReturn() causes a fatal error.
Choose the correct PHP code snippet that defines a generator function which yields values and returns a value.
Remember the syntax for yield and return in generators.
Option D correctly yields values then returns a value. Option D uses invalid yield return. Option D returns before yielding, so yields never run. Option D returns before second yield, so second yield is unreachable.
You have a generator that yields several values and then returns a final result. You want to iterate only the first two values and then get the return value. Which code snippet correctly achieves this?
<?php function gen() { yield 'a'; yield 'b'; yield 'c'; return 'done'; } $g = gen(); // Your code here
You must fully exhaust the generator to get the return value. Breaking early leaves it unfinished.
Option B uses next() to consume the first two values ('a' and 'b'), then exhausts the generator with an empty foreach to yield the remaining value ('c'), finally retrieving the return value 'done' with getReturn(). Options B and C break after the first two values without fully exhausting the generator, causing a fatal error. Option B attempts to get the return value before iteration starts.