Home > Backend Development > PHP Tutorial > PHP iterator implements the function of Fibonacci sequence_PHP tutorial

PHP iterator implements the function of Fibonacci sequence_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 10:25:18
Original
961 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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template