PHP基礎(chǔ)之生成器4——比較生成器和迭代器對(duì)象
生成器最大的優(yōu)勢(shì)就是簡單,和實(shí)現(xiàn)Iterator的類相比有著更少的樣板代碼,并且代碼的可讀性也更強(qiáng). 例如, 下面的函數(shù)和類是等價(jià)的:
<?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);} }?>
這種靈活性也付出了代價(jià):生成器是前向迭代器,不能在迭代啟動(dòng)之后往回倒. 這意味著同一個(gè)迭代器不能反復(fù)多次迭代: 生成器需要需要重新構(gòu)建調(diào)用,或者通過clone關(guān)鍵字克隆.
相關(guān)文章:
1. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問題2. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)3. vue實(shí)現(xiàn)web在線聊天功能4. idea配置jdk的操作方法5. Springboot 全局日期格式化處理的實(shí)現(xiàn)6. python 浮點(diǎn)數(shù)四舍五入需要注意的地方7. Docker容器如何更新打包并上傳到阿里云8. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法9. Java GZip 基于內(nèi)存實(shí)現(xiàn)壓縮和解壓的方法10. JAMon(Java Application Monitor)備忘記
