PHP基礎(chǔ)之生成器4——比較生成器和迭代器對象
生成器最大的優(yōu)勢就是簡單,和實現(xiàn)Iterator的類相比有著更少的樣板代碼,并且代碼的可讀性也更強. 例如, 下面的函數(shù)和類是等價的:
<?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);} }?>
這種靈活性也付出了代價:生成器是前向迭代器,不能在迭代啟動之后往回倒. 這意味著同一個迭代器不能反復(fù)多次迭代: 生成器需要需要重新構(gòu)建調(diào)用,或者通過clone關(guān)鍵字克隆.
相關(guān)文章:
1. python如何實現(xiàn)word批量轉(zhuǎn)HTML2. python excel和yaml文件的讀取封裝3. python3實現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)4. python爬蟲實戰(zhàn)之制作屬于自己的一個IP代理模塊5. moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決6. Android中的緩存7. 關(guān)于 Android WebView 的內(nèi)存泄露問題8. java——Byte類/包裝類的使用說明9. Python中內(nèi)建模塊collections如何使用10. Spring boot整合連接池實現(xiàn)過程圖解
