With Iterators
...
Collections:
Algorithms:
...
Iterators:
Algorithms are
decoupled
from collections!
1
2
3
4
1
4
5
3
2
Iterators in PHP
To create your own iterator class, implement Iterator :
To make a collection class iterable using a distinct iterator, implement IteratorAggregate :
interface Iterator extends Traversable {
function rewind();
function valid();
function current();
function key();
function next();
}
interface IteratorAggregate extends Traversable {
function getIterator();
}
Iterators in PHP
class MyList
implements IteratorAggregate {
private $nodes = ...;
function getIterator() {
return new MyListIterator( $this );
}
}
class MyGraph
implements IteratorAggregate {
private $nodes = ...;
private $edges = ...;
function getIterator() {
return new MyGraphIterator( $this );
}
}
function show( $collection ) {
foreach ( $collection as $node ) {
echo " $node <br/>" ;
}
}
echo show( new MyList);
echo show( new MyGraph);
Iterators in PHP
Traversable objects get special foreach treatment :
foreach ( $traversableObj as $key => $value ) {
// Loop body
}
// 1. Get the Iterator instance from $traversableObj:
if ( $traversableObj instanceof Iterator) {
$iterator = $traversableObj ;
} else if ( $traversableObj instanceof IteratorAggregate){
$iterator = $traversableObj ->getIterator();
}
// 2. Loop using the methods provided by Iterator:
$iterator ->rewind();
while ( $iterator ->valid()) {
$value = $iterator ->current();
$key = $iterator ->key();
// Loop body
$iterator ->next();
}
<=>
… is equivalent to ...
Note:
1 comments
Comments 1 - 1 of 1 previous next Post a comment