Bird
Raised Fist0
PHPprogramming~10 mins

Generator function execution model in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Generator function execution model
Call generator function
↓
First iteration: Start execution until yield
↓
Yield value to caller
↓
Pause execution
↓
Caller resumes generator
↓
Continue execution until next yield or return
↓
Repeat yield or finish
↓
Generator ends, return value or stop iteration
This flow shows how a PHP generator function runs: it starts, yields values one by one pausing after each, and resumes when the caller asks for the next value until it finishes.
Execution Sample
PHP
<?php
function countToThree() {
  yield 1;
  yield 2;
  yield 3;
}
$gen = countToThree();
foreach ($gen as $value) {
  echo $value . "\n";
}
This code defines a generator that yields numbers 1 to 3, then prints each number one by one.
Execution Table
StepActionGenerator StateYielded ValueOutput
1Call countToThree()Created, before first yieldnonenone
2First yield reachedPaused after yielding 111
3Resume generatorRunning, before second yieldnone1
4Second yield reachedPaused after yielding 222
5Resume generatorRunning, before third yieldnone2
6Third yield reachedPaused after yielding 333
7Resume generatorNo more yields, generator endsnone3
8Iteration endsGenerator finishednone3
💡 Generator ends after yielding all values; foreach loop stops.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6Final
$genGenerator object createdPaused at yield 1Paused at yield 2Paused at yield 3Finished
Key Moments - 2 Insights
Why does the generator pause after each yield instead of running all at once?
Because each yield sends a value back to the caller and pauses execution, waiting for the caller to request the next value (see steps 2, 4, 6 in execution_table).
What happens when the generator finishes all yields?
The generator ends and the foreach loop stops iterating (see step 7 and 8 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the generator state after the first yield?
AFinished
BRunning before first yield
CPaused after yielding 1
DNot started
💡 Hint
Check the 'Generator State' column at Step 2 in the execution_table.
At which step does the generator finish all yields and end?
AStep 4
BStep 7
CStep 6
DStep 8
💡 Hint
Look for 'No more yields, generator ends' in the 'Action' column.
If we add another yield after yield 3, how would the variable tracker change after Step 6?
AIt would show 'Paused at new yield 4'
BIt would show 'Finished' immediately
CIt would still show 'Paused at yield 3'
DIt would reset to 'Start'
💡 Hint
Variable tracker shows where the generator pauses after each yield (see current Step 6).
Concept Snapshot
PHP Generator Function:
- Use 'yield' to pause and send values one by one.
- Execution pauses at each yield until resumed.
- Caller uses foreach or next() to get values.
- Generator ends when no more yields.
- Saves memory by producing values on demand.
Full Transcript
This visual execution shows how a PHP generator function works step-by-step. Calling the generator function creates and returns a Generator object without starting execution. When the foreach starts its first iteration, execution begins and runs until it hits the first yield, then it pauses and sends that value to the caller. The caller receives the value and can use it, then asks the generator to continue. The generator resumes from where it paused, runs until the next yield, and pauses again. This repeats until the generator finishes all yields and ends. The foreach loop automatically handles this process, stopping when the generator is done. Variables track the generator's state, showing it pauses after each yield and finishes at the end.

Practice

(1/5)
1. What does the yield keyword do inside a PHP generator function?
easy
A. It pauses the function and returns a value to the caller.
B. It immediately ends the function and returns a value.
C. It creates a new variable inside the function.
D. It calls another function asynchronously.

Solution

  1. Step 1: Understand the role of yield in generators

    The yield keyword pauses the function execution and sends a value back to the caller without ending the function.
  2. Step 2: Compare with other options

    Unlike return, yield does not end the function but allows it to resume later.
  3. Final Answer:

    It pauses the function and returns a value to the caller. -> Option A
  4. Quick Check:

    yield pauses and returns value [OK]
Hint: Remember: yield pauses, return ends function [OK]
Common Mistakes:
  • Confusing yield with return
  • Thinking yield creates variables
  • Assuming yield calls other functions
2. Which of the following is the correct syntax to define a generator function in PHP?
easy
A. function gen() { return yield 1; }
B. function gen() { yield 1; }
C. function gen() => yield 1;
D. generator gen() { yield 1; }

Solution

  1. Step 1: Identify correct generator syntax

    In PHP, a generator function is a normal function that uses yield inside its body.
  2. Step 2: Check each option

    function gen() { yield 1; } uses a normal function with yield correctly. function gen() { return yield 1; } misuses return yield. function gen() => yield 1; uses invalid arrow syntax. generator gen() { yield 1; } uses an invalid keyword generator.
  3. Final Answer:

    function gen() { yield 1; } -> Option B
  4. Quick Check:

    Normal function + yield = generator [OK]
Hint: Generator = function with yield inside braces [OK]
Common Mistakes:
  • Using return with yield incorrectly
  • Trying arrow function syntax for generators
  • Using non-existent keywords like 'generator'
3. What will be the output of the following PHP code?
function gen() {
  yield 1;
  yield 2;
  yield 3;
}
foreach (gen() as $value) {
  echo $value . ' ';
}
medium
A. 123
B. Error: Cannot use foreach on generator
C. 1,2,3
D. 1 2 3

Solution

  1. Step 1: Understand generator yields

    The generator yields values 1, then 2, then 3 in sequence.
  2. Step 2: Analyze foreach output

    The foreach loops over each yielded value and echoes it followed by a space, so output is "1 2 3 "
  3. Final Answer:

    1 2 3 -> Option D
  4. Quick Check:

    foreach prints each yield with space [OK]
Hint: foreach prints each yield value in order [OK]
Common Mistakes:
  • Ignoring spaces in echo output
  • Thinking foreach can't iterate generators
  • Confusing output format with commas
4. Identify the error in this PHP generator function:
function gen() {
  yield 1;
  return 2;
  yield 3;
}
foreach (gen() as $v) {
  echo $v;
}
medium
A. Syntax error: return not allowed in generator
B. No error, outputs 123
C. The return ends generator early, so yield 3 is never reached
D. foreach cannot iterate generator with return

Solution

  1. Step 1: Understand return in generators

    Return ends the generator function immediately, so code after return is not executed.
  2. Step 2: Analyze code flow

    After yielding 1, the return 2 ends the generator, so yield 3 is never reached or yielded.
  3. Final Answer:

    The return ends generator early, so yield 3 is never reached -> Option C
  4. Quick Check:

    Return stops generator, later yields skipped [OK]
Hint: Return ends generator; yields after return ignored [OK]
Common Mistakes:
  • Thinking return causes syntax error
  • Expecting all yields to run despite return
  • Assuming foreach can't handle return in generator
5. Given this generator function, what will be the output?
function gen() {
  for ($i = 0; $i < 3; $i++) {
    yield $i => $i * 2;
  }
}
foreach (gen() as $key => $value) {
  echo "$key:$value ";
}
hard
A. 0:0 1:2 2:4
B. 0:0 1:1 2:2
C. 0 2 4
D. Error: Cannot yield key => value in PHP

Solution

  1. Step 1: Understand yield with key => value

    The generator yields keys 0,1,2 with values 0,2,4 respectively (value = key * 2).
  2. Step 2: Analyze foreach output

    foreach prints each key and value separated by colon and space, so output is "0:0 1:2 2:4 "
  3. Final Answer:

    0:0 1:2 2:4 -> Option A
  4. Quick Check:

    Yield key=>value prints key:value pairs [OK]
Hint: Yield key=>value pairs print as key:value [OK]
Common Mistakes:
  • Confusing value with key
  • Thinking yield key=>value is invalid
  • Ignoring spaces in output
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard