国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

PHP基礎之生成器4——比較生成器和迭代器對象

瀏覽:144日期:2022-09-15 09:50:00

生成器最大的優勢就是簡單,和實現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關鍵字克隆.

標簽: PHP
相關文章:
主站蜘蛛池模板: 得荣县| 昌黎县| 德庆县| 永顺县| 师宗县| 闵行区| 邵阳市| 潞城市| 南木林县| 辽阳市| 麦盖提县| 承德市| 紫云| 定襄县| 内江市| 黄陵县| 三台县| 颍上县| 芮城县| 湘潭县| 常熟市| 彭州市| 石城县| 金川县| 玉龙| 呼和浩特市| 青冈县| 安阳市| 开远市| 宁强县| 灵丘县| 许昌县| 固阳县| 堆龙德庆县| 仙桃市| 文昌市| 嘉善县| 元阳县| 霍城县| 交城县| 汨罗市|