首页 > 代码库 > 用PHP迭代器来实现一个斐波纳契数列

用PHP迭代器来实现一个斐波纳契数列

斐波纳契数列通常做法是用递归实现,当然还有其它的方法。这里现学现卖,用PHP的迭代器来实现一个斐波纳契数列,几乎没有什么难度,只是把类里的next()方法重写了一次。注释已经写到代码中,也是相当好理解的。定州市科技工业局

view source
 
print?
01/**
02* @author 简明现代魔法 http://www.nowamagic.net
03*/
04class Fibonacci implements Iterator {
05private $previous = 1;
06private $current = 0;
07private $key = 0;
08 
09public function current() {
10return $this->current;
11}
12 
13public function key() {
14return $this->key;
15}
16 
17public function next() {
18// 关键在这里
19// 将当前值保存到 $newprevious
20$newprevious = $this->current;
21// 将上一个值与当前值的和赋给当前值
22$this->current += $this->previous;
23// 前一个当前值赋给上一个值
24$this->previous = $newprevious;
25$this->key++;
26}
27 
28public function rewind() {
29$this->previous = 1;
30$this->current = 0;
31$this->key = 0;
32}
33 
34public function valid() {
35return true;
36}
37}
38 
39$seq = new Fibonacci;
40$i = 0;
41foreach ($seq as $f) {
42echo "$f ";
43if ($i++ === 15) break;
44}

程序运行结果:

view source
 
print?
10 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

用PHP迭代器来实现一个斐波纳契数列