<?php
class FibonacciIterator implements Iterator
{
public function __construct($maxNum = 1000)
{
$this->MAX_NUM = $maxNum;
$this->rewind();
}
public function rewind()
{
$this->pos = 0;
$this->pre = 0;
$this->cur = 1;
}
public function current()
{
return $this->cur;
}
public function key()
{
return $this->pos;
}
public function valid()
{
return $this->pos < $this->MAX_NUM;
}
public function next()
{
$newpre = $this->cur;
$this->cur += $this->pre;
$this->pre = $newpre;
$this->pos++;
}
}
$fibiter = new FibonacciIterator();
foreach ($fibiter as $key => $val) {
echo $key . ':' . $val . " ";
}