The Iterator is an interface for external iterators or objects that can be iterated themselves internally. In PHP, it is defined as follows.
Iterator extends Traversable
{
/* Methods */
abstract public mixed current ( void )
abstract public scalar key ( void )
abstract public void next ( void )
abstract public void rewind ( void )
abstract public boolean valid ( void )
}
The following presents a simply clear example that computes the Fibonacci sequence using Iterator. The Fibonacci Number is very well known, probably due to its recursive definition. [read this]
By implementing the above six methods, the following class can be used as a iterator, e.g. in the foreach statement. The valid tells if the current position is OK, if not, the foreach loop will terminate.
class Fib implements Iterator
{
private $previous = 1;
private $current = 0;
private $key = 0;
public function __construct()
{
$this->rewind();
}
public function key()
{
return($this->key);
}
public function current()
{
return($this->current);
}
public function next()
{
$n = $this->current;
$this->current += $this->previous;
$this->previous = $n;
$this->key++;
}
public function rewind()
{
$this->previous = 1;
$this->current = 0;
$this->key = 0;
}
public function valid()
{
return(true);
}
}
$seq = new Fib();
$i = 0;
foreach ($seq as $f)
{
echo ($f);
if ($i++ === 10)
{
break;
}
}
–EOF (The Ultimate Computing & Technology Blog) —
272 wordsLast Post: Index Sorting in PHP
Next Post: Easy Timeit Function in Python
