码迷,mamicode.com
首页 > Web开发 > 详细

php迭代器

时间:2017-09-15 20:25:43      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:lib   .net   bre   blog   迭代   each   turn   imp   gic   

<?php

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, ‘<br>‘; 
    if ($i++ === 15) break; 
} 

 原理:http://www.nowamagic.net/librarys/veda/detail/2161

php迭代器

标签:lib   .net   bre   blog   迭代   each   turn   imp   gic   

原文地址:http://www.cnblogs.com/mljun/p/7527729.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!