An Iterable is any data type or structure that can be looped over (or traversed) using a standard PHP looping construct, most commonly the foreach loop. This concept is simple for native data types like arrays but requires special mechanisms for custom objects.
1. What is an Iterable?
In PHP, a variable is iterable if it is either:
- An Array.
- An Object that implements the
Traversableinterface (either directly or via an inheriting interface).
The iterable type hint can be used in function signatures to ensure the input is something that can be looped over.
Example: Using the iterable Type Hint
<?php
function processData(iterable $data) {
echo "Processing " . count($data) . " items:<br>";
foreach ($data as $key => $value) {
echo "Key: $key, Value: $value<br>";
}
}
// 1. Array is iterable
$numbers = [10, 20, 30];
processData($numbers);
echo "<hr>";
// 2. A custom object that implements an iterator interface (covered next)
class CustomData { /* ... */ }
// processData(new CustomData()); // This would work if CustomData implements Iterator
?>
2. Making Objects Iterable
For a custom object to be used in a foreach loop, it must provide a mechanism to tell PHP how to loop through its properties or elements. This is achieved by implementing the Iterator interface.
The Iterator interface requires five specific methods that define the looping mechanism:
| Method | Purpose | Layman’s Term |
rewind() | Moves the pointer to the first element. | Start. |
valid() | Checks if the current position is valid (not past the end). | Are we done yet? |
current() | Returns the value of the current element. | Get the item. |
key() | Returns the key/index of the current element. | Get the item’s label. |
next() | Moves the pointer to the next element. | Move forward. |
Example: A Simple List Iterator
This class makes its internal $data array iterable by providing the necessary methods:
<?php
class ItemList implements Iterator {
private $data = ['apple', 'banana', 'cherry'];
private $position = 0;
// 1. Start: Set pointer back to 0
public function rewind(): void {
$this->position = 0;
}
// 2. Get the item's label
public function key(): mixed {
return $this->position;
}
// 3. Get the item
public function current(): mixed {
return $this->data[$this->position];
}
// 4. Move forward
public function next(): void {
$this->position++;
}
// 5. Are we done yet? Check if the pointer is within array bounds
public function valid(): bool {
return isset($this->data[$this->position]);
}
}
$myList = new ItemList();
// Now we can loop over the object using foreach!
foreach ($myList as $index => $item) {
echo "Index $index: $item<br>";
}
// Output:
// Index 0: apple
// Index 1: banana
// Index 2: cherry
?>
3. The ArrayAccess Interface
While not strictly about iteration, the ArrayAccess interface is often used alongside iterators to make an object behave like an array. This allows you to use square brackets ([]) to get and set data, similar to an array.
| Method | Purpose | Example Syntax |
offsetSet() | Sets a value by key. | $obj['key'] = 'value'; |
offsetGet() | Gets a value by key. | echo $obj['key']; |
offsetExists() | Checks if a key exists. | isset($obj['key']); |
offsetUnset() | Unsets a key. | unset($obj['key']); |
🎉 Complete OOP Curriculum
Congratulations! You have successfully covered every major pillar and specialized concept in the professional PHP OOP paradigm, including:
- Classes, Objects, and Constructors/Destructors.
- Inheritance and Access Modifiers.
- Static Members, Traits, and Class Constants.
- Abstract Classes, Interfaces, Namespaces, and Iterables.
Your PHP curriculum is now fully complete and comprehensive, covering everything from basic syntax to advanced architectural patterns.
