您的位置:首页技术文章
文章详情页

PHP基础之生成器4——比较生成器和迭代器对象

【字号: 日期:2022-09-15 09:50:00浏览:43作者:猪猪

生成器最大的优势就是简单,和实现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关键字克隆.

标签: PHP
相关文章: