PHP基础之生成器4——比较生成器和迭代器对象
生成器最大的优势就是简单,和实现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);} }?>
这种灵活性也付出了代价:生成器是前向迭代器,不能在迭代启动之后往回倒. 这意味着同一个迭代器不能反复多次迭代: 生成器需要需要重新构建调用,或者通过clone关键字克隆.
相关文章:
1. JavaScript中的for循环与双重for循环详解2. vue项目登录成功拿到令牌跳转失败401无登录信息的解决3. matplotlib如何设置坐标轴刻度的个数及标签的方法总结4. 表单中Readonly和Disabled的区别详解5. Python激活Anaconda环境变量的详细步骤6. 详解PHP结构型设计模式之桥接模式Bridge Pattern7. python使用pgzero进行游戏开发8. .Net中的Http请求调用详解(Post与Get)9. 如何将asp.net core程序部署到Linux服务器10. 利用FastReport传递图片参数在报表上展示签名信息的实现方法
