迭代器

<?php

/**
 * 迭代器
 * 使用php Iterator接口
 *
 * 迭代器在遍历大文件,或者大数据的时候很有用,因为它不需要将数据一次性取出,而是即取即用。
 * 使用yield生成器也可以实现相同效果。
 */
class fileLineIterator implements Iterator {
    private $cur = NULL;
    private $nxt = NULL;
    private $lineCount = 0;
    
    public function __construct($filename) {
        $this->fp = fopen($filename, 'r');
    }
    
    //在每次迭代之前初始化某些操作
    public function rewind() {
        rewind($this->fp);
        $this->cur = fgets($this->fp);
        $this->nxt = fgets($this->fp);
        return true;
    }
    
    //获取当前元素的键
    public function key() {
        return $this->lineCount++;
    }
    
    //获取当前元素的值
    public function current() {
        return $this->cur;
    }
    
    //元素向前推一位
    public function next() {
        $this->cur = $this->nxt;
        $this->nxt = fgets($this->fp);
    }
    
    //通过该操作判断迭代是否应该结束
    public function valid() {
        return $this->cur===FALSE?FALSE:TRUE;
    }
}

$fileIter = new fileLineIterator('test_iterator.txt');

foreach($fileIter as $line) {
    var_dump($line,$fileIter->current());
}
原文地址:https://www.cnblogs.com/mtima/p/3181338.html