PHP基础之生成器4——比较生成器和迭代器对象
2014-11-07 00:00
1256 查看
生成器最大的优势就是简单,和实现Iterator的类相比有着更少的样板代码,并且代码的可读性也更强. 例如, 下面的函数和类是等价的:
<?php function getLinesFromFile($fileName) { if (!$fileHandle = fopen($fileName, 'r')) { return; } while (false !== $line = fgets($fileHandle)) { yield $line; } fclose($fileHandle); } // versus... class LineIterator implements Iterator { protected $fileHandle; protected $line; protected $i; public function __construct($fileName) { if (!$this->fileHandle = fopen($fileName, 'r')) { throw new RuntimeException('Couldn\'t open file "' . $fileName . '"'); } } public function rewind() { fseek($this->fileHandle, 0); $this->line = fgets($this->fileHandle); $this->i = 0; } public function valid() { return false !== $this->line; } public function current() { return $this->line; } public function key() { return $this->i; } public function next() { if (false !== $this->line) { $this->line = fgets($this->fileHandle); $this->i++; } } public function __destruct() { fclose($this->fileHandle); } } ?>
相关文章推荐
- PHP基础之类和对象18——对象比较
- PHP基础之生成器3——生成器对象
- php基础知识:类与对象(4) 范围解析操作符(::)
- php基础知识:类与对象(3) 构造函数和析构函数
- PHP 4 中对象的比较
- PHP面向对象基础知识总结(2012-07-11)
- PHP面向对象学习笔记之一:基础概念
- 用比较的方法认识PHP的面向对象
- PHP面向对象学习笔记之一 基础概念
- C#基础之数组排序,对象大小比较
- C#基础之数组排序,对象大小比较
- PHP基础知识系列:面向对象基础
- php基础知识:类与对象(2) 自动加载对象
- php基础知识:类与对象(2) 自动加载对象
- php基础知识:类与对象(3) 构造函数和析构函数
- PHP和Mysqlweb应用开发核心技术-第1部分 Php基础-4 面各对象的程序设计
- 比较两种php调用Java对象的方法
- php基础知识:类与对象(4) 范围解析操作符(::)
- php面向对象全攻略 (一) 面向对象基础知识
- PHP 5 中对象的比较