生成器最大的优势就是简单,和实现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关键字克隆.
- 本文固定链接: https://www.zxbcw.cn/post/1154/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)