0
0
PHPprogramming~10 mins

IteratorAggregate interface in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - IteratorAggregate interface
Create class implementing IteratorAggregate
Define getIterator() method
Inside getIterator(), return an Iterator object
Use foreach on class instance
foreach calls getIterator()
Iterate over returned Iterator
Access each element in loop
End
This flow shows how a class implements IteratorAggregate by defining getIterator() which returns an iterator used by foreach to loop over elements.
Execution Sample
PHP
<?php
class MyCollection implements IteratorAggregate {
  private array $items = ["apple", "banana", "cherry"];
  public function getIterator(): Traversable {
    return new ArrayIterator($this->items);
  }
}
foreach (new MyCollection() as $item) {
  echo $item . "\n";
}
This code defines a class that returns an iterator over an array, then loops over it printing each item.
Execution Table
StepActionCode LineResult/Output
1Create MyCollection instance$collection = new MyCollection();Object created with items ["apple", "banana", "cherry"]
2foreach starts looping over $collectionforeach (new MyCollection() as $item)Calls getIterator() method
3Call getIterator()public function getIterator()Returns ArrayIterator over items
4First iterationecho $item . "\n";Outputs: apple
5Second iterationecho $item . "\n";Outputs: banana
6Third iterationecho $item . "\n";Outputs: cherry
7No more itemsforeach endsLoop ends, iteration stops
💡 Iteration stops when ArrayIterator has no more elements.
Variable Tracker
VariableStartAfter Step 4After Step 5After Step 6Final
$items["apple", "banana", "cherry"]["apple", "banana", "cherry"]["apple", "banana", "cherry"]["apple", "banana", "cherry"]["apple", "banana", "cherry"]
$itemundefinedapplebananacherryundefined (loop ended)
Key Moments - 3 Insights
Why does foreach call getIterator() on the object?
Because the class implements IteratorAggregate, foreach looks for getIterator() to get an iterator to loop over, as shown in execution_table step 2 and 3.
What type of object must getIterator() return?
It must return an object implementing Traversable, like ArrayIterator, so foreach can iterate over it (see step 3).
Why does $item change each iteration?
$item gets assigned the current element from the iterator each loop cycle, shown in steps 4, 5, and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output at step 5?
Aapple
Bbanana
Ccherry
DNo output
💡 Hint
Check the 'Result/Output' column for step 5 in execution_table.
At which step does foreach call getIterator()?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'Action' column describing foreach starting and calling getIterator().
If getIterator() returned a non-iterator object, what would happen?
ALoop would run zero times silently
Bforeach would loop normally
CPHP would throw an error
DOutput would be empty strings
💡 Hint
Recall that getIterator() must return Traversable; otherwise, foreach cannot iterate (see key_moments).
Concept Snapshot
IteratorAggregate interface:
- Implement IteratorAggregate in your class
- Define getIterator() method
- getIterator() returns an iterator (implements Traversable)
- foreach uses getIterator() to loop
- Enables custom iteration over objects
Full Transcript
This example shows how a PHP class uses the IteratorAggregate interface to allow foreach loops over its data. The class defines getIterator() which returns an ArrayIterator over an internal array. When foreach runs, it calls getIterator() to get the iterator, then loops over each element, assigning it to the loop variable and printing it. The execution table traces each step: creating the object, calling getIterator(), and each iteration output. Variables like $item change each loop. Key points include that foreach calls getIterator() automatically on objects implementing IteratorAggregate, and getIterator() must return an iterator object. If it doesn't, PHP throws an error. This pattern helps make objects iterable in a simple, flexible way.