php使用Iterator接口,逐行遍历文件

来源:互联网 发布:网络公开课网站 编辑:程序博客网 时间:2024/04/28 21:33

定义接口Iterator如下所示

interface Iterator

{

    public function rewind(); //将迭代器倒回到第一个元素

    public function next();     //向前移到下一个元素

   public function key();       //返回当前元素值

   public function current();//返回当前的元素

   public function valid();    //检查当前元素是否有效

}

实现接口Iterator的任何类都可以在for循环使用,他们的对象被成为迭代器

<!DOCTYPE html>  <html>  <head>  <title>使用Iterator接口,逐行遍历文件</title>  <meta charset="utf-8">  </head>  <body>  <p>使用Iterator接口,逐行遍历文件</p>  <?php  class file_iter implements iterator{private $fp;private $index = 0;private $line;function __construct($name){$fp = fopen($name, "r");if(!$fp){die("Cannot open $name for reading");}$this->fp = $fp;$this->line = rtrim(fgets($this->fp), "\n");}function rewind(){$this->index = 0;rewind($this->fp);$this->line = rtrim(fgets($this->fp), "\n");}function current(){return ($this->line);}function key(){return ($this->index);}function next(){$this->index++;$this->line = rtrim(fgets($this->fp), "\n");if(!feof($this->fp)){return ($this->line);}else{return (NULL);}}function valid(){return (feof($this->fp) ? FALSE : TRUE);}}$x = new file_iter("words/english-words.10");foreach($x as $lineno => $val){print "$lineno: $val <br />";}?>  </body>  </html>  


0 0