<?php
class FibonacciIterator implements Iterator
{
public function __construct($maxNum = 1000)
{
$this->MAX_NUM = $maxNum;
$this->rewind();
}
public function rewind()
{
$this->pos = 0; // key
$this->pre = 0; // previous
$this->cur = 1; // current
}
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();
// Result: 0:1 1:1 2:2 3:3 4:5 5:8 6:13 ...
foreach ($fibiter as $key => $val) {
echo $key . ':' . $val . " ";
}
PHP迭代器实现斐波那契数列
最新推荐文章于 2025-04-10 23:42:34 发布