代码如下:
class Fibonacci implements Iterator {
private $prevIoUs = 1;
private $current = 0;
private $key = 0; public function current() {
return $this->current;
} public function key() {
return $this->key;
} public function next() {
// 关键在这里
// 将当前值保存到 $newprevIoUs
$newprevIoUs = $this->current;
// 将上一个值与当前值的和赋给当前值
$this->current += $this->prevIoUs;
// 前一个当前值赋给上一个值
$this->prevIoUs = $newprevIoUs;
$this->key++;
} public function rewind() {
$this->prevIoUs = 1;
$this->current = 0;
$this->key = 0;
} public function valid() {
return true;
}
}
private $prevIoUs = 1;
private $current = 0;
private $key = 0; public function current() {
return $this->current;
} public function key() {
return $this->key;
} public function next() {
// 关键在这里
// 将当前值保存到 $newprevIoUs
$newprevIoUs = $this->current;
// 将上一个值与当前值的和赋给当前值
$this->current += $this->prevIoUs;
// 前一个当前值赋给上一个值
$this->prevIoUs = $newprevIoUs;
$this->key++;
} public function rewind() {
$this->prevIoUs = 1;
$this->current = 0;
$this->key = 0;
} public function valid() {
return true;
}
}
$seq = new Fibonacci;
$i = 0;
foreach ($seq as $f) {
echo "$f ";
if ($i++ === 15) break;
}
程序运行结果:
代码如下:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
原文链接:https://www.f2er.com/php/25463.html