What it is and why to use it
A collection object may need to control how it stores data while still working with foreach. IteratorAggregate lets the object supply a separate Traversable through getIterator(). This keeps its public API about iteration rather than requiring callers to know the internal array property. PHP’s iterable type accepts arrays and Traversable objects, so a consumer can support both.
How it works
Implement IteratorAggregate and return an iterator such as ArrayIterator, or a Generator, from public getIterator(): Traversable. Returning a fresh iterator each time lets independent foreach loops start their own traversal. Returning a raw array does not satisfy getIterator’s Traversable return type, even though arrays themselves work with foreach. An iterable declaration does not specify element types or promise that every possible iterable is reusable.
Common mistakes and limitations
Do not claim that wrapping an array automatically makes it lazy or saves memory: ArrayIterator still works over supplied data. A standalone generator is generally single-pass. Decide whether your collection promises repeatable traversal and whether callers may mutate values during iteration.
Run the examples locally
Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.
The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.
These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.
Check your interpreter, lint and run one saved example
php -v
php -l example.php
php example.phpContinue learning
Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.
Syntax
class Lessons implements IteratorAggregate { public function getIterator(): Traversable { return new ArrayIterator([]); } }Examples
Iterate over a small collection object
Return a fresh ArrayIterator for each traversal of private lesson names.
<?php
declare(strict_types=1);
class Lessons implements IteratorAggregate {
public function __construct(private array $names) {}
public function getIterator(): Traversable {
return new ArrayIterator($this->names);
}
}
$lessons = new Lessons(['Arrays', 'Functions']);
foreach ($lessons as $position => $name) {
echo $position, ': ', $name, PHP_EOL;
}
- The names property stays private; foreach requests the iterator through getIterator.
- ArrayIterator presents the array’s keys and values without requiring a custom Iterator implementation.
- Each loop can request a fresh iterator. This example stores all names in memory and does not claim streaming behaviour.
- Expected output: 0: Arrays 1: Functions
Accept both arrays and iterator objects
Write a consumer against iterable rather than a single storage type.
<?php
declare(strict_types=1);
function joined(iterable $names): string {
$collected = [];
foreach ($names as $name) {
$collected[] = $name;
}
return implode(', ', $collected);
}
echo joined(['PHP', 'Ruby']), PHP_EOL;
echo joined(new ArrayIterator(['Lua', 'Luau'])), PHP_EOL;
- The iterable parameter accepts both the ordinary array and the Traversable ArrayIterator.
- The same foreach body collects values from either source, then joins them.
- This consumer deliberately materialises the results; it is convenient for a small display list, not a memory-bounded processor for huge or infinite iterables.
- Expected output: PHP, Ruby Lua, Luau
Best practices
- Keep iteration separate from the collection’s private storage.
- Document whether traversal can be repeated and what value types are yielded.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual