方法一:迭代器class myIterator implements Iterator { private $position = 0; private $current = 1; private $previous = 0; public function __construct(){} public function rewind() { $this->position = 0; $this->current = 1; $this->previous = 0; } public function current() { return $this->current; } public function key() { return $this->position; } public function next() { $tem = $this->previous; $this->previous = $this->current; $this->current = $this->current + $tem; ++$this->position; } public function valid() { return ($this->current !== false); }} $it = new myIterator;foreach($it as $key => $value) { // if ($key > 15) break; echo "$value ";}
方法二:生成器function generator(){ $current = 1; $previous = 0; while ($current) { yield $current; // 重点在这里使用了yield $temp = $current; $current = $current + $previous; $previous = $temp; }}foreach (generator() as $key => $value) { // if ($key > 15) break; echo "$value ";}