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

PHP iterator implements the function of Fibonacci sequence_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:18916browse

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; }...
Statement:
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