Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
PHP Traversable interface
The Traversable interface is PHP's base interface for making objects work with foreach loops. It's an abstract interface that cannot be implemented directly − instead, you implement either Iterator or IteratorAggregate which extend Traversable.
Syntax
Traversable {
// No methods - this is an abstract interface
}
Using IteratorAggregate
The simplest way to make a class traversable is by implementing IteratorAggregate ?
<?php
class MyCollection implements IteratorAggregate {
private $items = [];
public function addItem($item) {
$this->items[] = $item;
}
public function getIterator(): Traversable {
return new ArrayIterator($this->items);
}
}
$collection = new MyCollection();
$collection->addItem("Apple");
$collection->addItem("Banana");
$collection->addItem("Cherry");
// Now we can use foreach
foreach ($collection as $item) {
echo $item . "<br>";
}
?>
Apple Banana Cherry
Using Iterator Interface
For more control, implement the Iterator interface directly ?
<?php
class NumberRange implements Iterator {
private $start;
private $end;
private $current;
public function __construct($start, $end) {
$this->start = $start;
$this->end = $end;
}
public function rewind(): void {
$this->current = $this->start;
}
public function current() {
return $this->current;
}
public function key() {
return $this->current;
}
public function next(): void {
$this->current++;
}
public function valid(): bool {
return $this->current <= $this->end;
}
}
$range = new NumberRange(1, 5);
foreach ($range as $number) {
echo "Number: $number<br>";
}
?>
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
Checking if Object is Traversable
Use instanceof to check if an object implements Traversable ?
<?php
class SimpleClass {}
class TraversableClass implements IteratorAggregate {
public function getIterator(): Traversable {
return new ArrayIterator([1, 2, 3]);
}
}
$simple = new SimpleClass();
$traversable = new TraversableClass();
var_dump($simple instanceof Traversable); // false
var_dump($traversable instanceof Traversable); // true
?>
bool(false) bool(true)
Conclusion
Traversable enables custom objects to work with foreach. Use IteratorAggregate for simple cases or Iterator for full control over the iteration process.
Advertisements
