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
PHP Iterable interface
The Iterator interface extends the abstract Traversable interface in PHP. It allows user-defined classes to become iterable using foreach loops. PHP provides many built-in iterators (called SPL iterators) like ArrayIterator, DirectoryIterator, etc. A user class implementing the Iterator interface must implement all its abstract methods.
Syntax
Iterator extends Traversable {
/* Methods */
abstract public current ( void ) : mixed
abstract public key ( void ) : scalar
abstract public next ( void ) : void
abstract public rewind ( void ) : void
abstract public valid ( void ) : bool
}
Methods
The Iterator interface requires implementing these five methods ?
- current() − Return the current element
- key() − Return the key of the current element
- next() − Move forward to next element
- rewind() − Rewind the Iterator to the first element
- valid() − Checks if current position is valid
Example
Here's a complete example of a class implementing the Iterator interface ?
<?php
class myIterator implements Iterator {
private $index = 0;
private $arr = array(10,20,30,40);
public function __construct() {
$this->index = 0;
}
public function rewind() {
$this->index = 0;
}
public function current() {
return $this->arr[$this->index];
}
public function key() {
return $this->index;
}
public function next() {
++$this->index;
}
public function valid() {
return isset($this->arr[$this->index]);
}
}
// Using foreach loop
$it = new myIterator();
foreach($it as $key => $value) {
echo "$key=>" . $value . "<br>";
}
echo "<br>";
// Using manual iteration
$it->rewind();
do {
echo $it->key() . "=>" . $it->current() . "<br>";
$it->next();
}
while ($it->valid());
?>
0=>10 1=>20 2=>30 3=>40 0=>10 1=>20 2=>30 3=>40
How It Works
When using foreach on an Iterator object, PHP automatically calls ?
- rewind() − Reset to beginning
- valid() − Check if current position exists
- current() and key() − Get current value and key
- next() − Move to next position
- Repeat steps 2-4 until valid() returns false
Conclusion
The Iterator interface provides a standardized way to make custom classes iterable with foreach loops. By implementing the five required methods, you can control exactly how your objects are traversed.
