The IteratorAggregate interface helps you make your objects easy to loop over with foreach. It tells PHP how to get an iterator for your object.
0
0
IteratorAggregate interface in PHP
Introduction
When you want to allow users to loop through your custom object like an array.
When your object holds a collection of items and you want to control how they are accessed.
When you want to separate the logic of storing data from the logic of iterating over it.
Syntax
PHP
class ClassName implements IteratorAggregate { public function getIterator(): Traversable { // return an iterator object here } }
The getIterator() method must return an object that implements Traversable, usually an ArrayIterator.
This interface makes your object compatible with foreach loops.
Examples
This example shows a class that holds fruits and allows looping through them with foreach.
PHP
<?php class MyCollection implements IteratorAggregate { private array $items = []; public function __construct(array $items) { $this->items = $items; } public function getIterator(): Traversable { return new ArrayIterator($this->items); } } $collection = new MyCollection(['apple', 'banana', 'cherry']); foreach ($collection as $item) { echo $item . "\n"; }
This example creates a range of numbers and lets you loop through them easily.
PHP
<?php class NumberRange implements IteratorAggregate { private int $start; private int $end; public function __construct(int $start, int $end) { $this->start = $start; $this->end = $end; } public function getIterator(): Traversable { return new ArrayIterator(range($this->start, $this->end)); } } $range = new NumberRange(1, 3); foreach ($range as $number) { echo $number . "\n"; }
Sample Program
This program creates a shopping list object that can be looped over with foreach to print each item.
PHP
<?php class ShoppingList implements IteratorAggregate { private array $items; public function __construct(array $items) { $this->items = $items; } public function getIterator(): Traversable { return new ArrayIterator($this->items); } } $list = new ShoppingList(['milk', 'bread', 'eggs']); foreach ($list as $item) { echo "Buy: $item\n"; }
OutputSuccess
Important Notes
You can return any iterator from getIterator(), not just ArrayIterator.
Implementing IteratorAggregate is simpler than Iterator if you just want to provide an iterator.
Summary
The IteratorAggregate interface lets your object be used in foreach loops.
You must implement getIterator() to return an iterator.
This helps separate data storage from how you loop through data.