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關鍵字克隆.
相關文章: