使用了SPL的 迭代器, 可以直接对打开的文件进行foreach读取, 类的构造如下
class FileIterator implements Iterator { private $fp; private $line_num; private $line; public function __construct($filename) { $fp = @fopen($filename, ‘r‘); if (!$fp) { throw new Exception("file ".$filename." is not exists"); } $this->fp = $fp; } public function key() { return $this->line_num; } public function current() { return $this->line; } public function rewind() { rewind($this->fp); } public function next() { } public function valid() { $this->line = fgets($this->fp); $this->line_num++; return $this->line != false; } }
使用方法
foreach(new fileIterator(‘./test.txt‘) as $k => $line) { echo $k."->".$line; }
可以再包装一个方法在对象的构造上,这样就不用显示的去构造类了。
原文地址:http://www.cnblogs.com/sailrancho/p/3811707.html