斐波纳契数列通常做法是用递归实现,当然还有其它的方法。这里现学现卖,用PHP的迭代器来实现一个斐波纳契数列,几乎没有什么难度,只是把类里的next()方法重写了一次。注释已经写到代码中,也是相当好理解的。
01 |
/** |
02 |
* @author 简明现代魔法 http://www.nowamagic.net |
03 |
*/ |
04 |
class Fibonacci implements Iterator {
|
05 |
private $previous = 1;
|
06 |
private $current = 0;
|
07 |
private $key = 0;
|
08 |
09 |
public function current() {
|
10 |
return $this ->current;
|
11 |
}
|
12 |
13 |
public function key() {
|
14 |
return $this ->key;
|
15 |
}
|
16 |
17 |
public 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 |
28 |
public function rewind () {
|
29 |
$this ->previous = 1;
|
30 |
$this ->current = 0;
|
31 |
$this ->key = 0;
|
32 |
}
|
33 |
34 |
public function valid() {
|
35 |
return true;
|
36 |
}
|
37 |
} |
38 |
39 |
$seq = new Fibonacci;
|
40 |
$i = 0;
|
41 |
foreach ( $seq as $f ) {
|
42 |
echo "$f " ;
|
43 |
if ( $i ++ === 15) break ;
|
44 |
} |
程序运行结果:
1 |
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 |