Home > Backend Development > PHP Tutorial > How to use PHP iterator to implement a Fibonacci sequence

How to use PHP iterator to implement a Fibonacci sequence

藏色散人
Release: 2023-04-07 21:58:02
forward
2494 people have browsed it

The Fibonacci sequence is usually implemented recursively, but of course there are other methods. Here you can learn and sell now. It is almost not difficult to use PHP iterator to implement a Fibonacci sequence. You just need to rewrite the next() method in the class.

Comments have been written into the code and are quite easy to understand.

/**
* @author 简明现代魔法 http://www.nowamagic.net
*/
class Fibonacci implements Iterator { 
    private $previous = 1; 
    private $current = 0; 
    private $key = 0; 
    
    public function current() { 
        return $this->current; 
    } 
    
    public function key() { 
        return $this->key; 
    } 
    
    public function next() { 
// 关键在这里
// 将当前值保存到  $newprevious
        $newprevious = $this->current; 
// 将上一个值与当前值的和赋给当前值
        $this->current += $this->previous; 
// 前一个当前值赋给上一个值
        $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; 
}
Copy after login

Program running results:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
Copy after login

Recommended: "PHP Tutorial"

The above is the detailed content of How to use PHP iterator to implement a Fibonacci sequence. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:nowamagic
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