您的位置:首页 > 编程语言 > PHP开发

PHP基础之生成器4——比较生成器和迭代器对象

2014-11-07 00:00 1256 查看
生成器最大的优势就是简单,和实现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);
        }
    }
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PHP基础