Iterator interface extends the abstract Traversable interface. PHP provides a number of built-in iterators (called SPL iterators) for many common functions. For example ArrayIterator, DirectoryIterator, etc. User classes that implement the Iterator interface should implement the abstract methods defined in it.
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 }
Iterator::current — Returns the current element
Iterator::key —Returns the key of the current element
Iterator::next — Move to the next element
Iterator::rewind — Rewind the iterator to the first element
Iterator::valid — Check if the current position is valid
When implementing the IteratorAggregate or Iterator interface, they must be listed before their name in the implements clause.
In the following PHP script, a class that implements an interface contains a private variable as an array. By implementing the abstract method of iterator, we can iterate over the array using the foreach loop and the next() method.
<?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 a foreach loop, we can iterate over the array properties of the MyIterator object
$it = new myIterator(); foreach($it as $key => $value) { echo "$key=>". $value ."</p><p>"; }
Iteration can also be done by calling it in a while loopnext() method to execute. Make sure to rewind the iterator before starting the loop.
$it->rewind(); do { echo $it->key() . "=>" .$it->current() . "</p><p>"; $it->next(); } while ($it->valid());
In both cases, the traversal over the array properties shows the following results
0=>10 1=>20 2=>30 3=>40
The above is the detailed content of PHP Iterable interface. For more information, please follow other related articles on the PHP Chinese website!