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. 基于android studio的layout的xml文件的創(chuàng)建方式2. 解決Android studio xml界面無法預(yù)覽問題3. 詳解Android studio 動態(tài)fragment的用法4. 圖文詳解vue中proto文件的函數(shù)調(diào)用5. 什么是python的自省6. Spring Boot和Thymeleaf整合結(jié)合JPA實現(xiàn)分頁效果(實例代碼)7. Android如何加載Base64編碼格式圖片8. 使用Android studio查看Kotlin的字節(jié)碼教程9. Vuex localStorage的具體使用10. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實現(xiàn)

網(wǎng)公網(wǎng)安備