PHP iterator implements the function of Fibonacci sequence_PHP tutorial

WBOY
Release: 2016-07-13 10:25:18
Original
918 people have browsed it

Copy code The code is as follows:

class Fibonacci implements Iterator {
private $previous = 1;
private $current = 0;
private $key = 0;

public function current() {
return $this->current;
}

public function key () {
                                                                                                                                                            """""""""""""""
$newprevious = $this->current;
// Assign the sum of the previous value and the current value to the current value
$this->current += $this->previous;
// Assign the previous current value to the previous value
$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;

}


Program execution result:


Copy code

The code is as follows:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610


http://www.bkjia.com/PHPjc/825140.htmlwww.bkjia.com

truehttp: //www.bkjia.com/PHPjc/825140.htmlTechArticleCopy the code code as follows: class Fibonacci implements Iterator { private $previous = 1; private $current = 0; private $ key = 0; public function current() { return $this-current; }...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!