生成器不能处于闭包状态

Generator cannot be in a Closure

我正在创建一个 class,它在调用特定方法时使用生成器生成 return 值,例如:

class test {
    protected $generator;

    private function getValueGenerator() {
        yield from [1,1,2,3,5,8,13,21];
    }

    public function __construct() {
        $this->generator = $this->getValueGenerator();
    }

    public function getValue() {
        while($this->generator->valid()) {
            $latitude = $this->generator->current();
            $this->generator->next();
            return $latitude;
        }
        throw new RangeException('End of line');
    }
}

$line = new test();

try {
    for($i = 0; $i < 10; ++$i) {
        echo $line->getValue();
        echo PHP_EOL;
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

当生成器被定义为 class 本身中的方法时,它工作得很好......但我想让它更动态,并使用闭包作为生成器,比如:

class test {
    public function __construct() {
        $this->generator = function() {
            yield from [1,1,2,3,5,8,13,21];
        };
    }
}

不幸的是,当我尝试 运行 这个时,我得到

Fatal error: Uncaught Error: Call to undefined method Closure::valid()

在对 getValue()

的调用中

任何人都可以解释为什么我不能这样调用生成器的实际逻辑吗?我如何才能使用闭包而不是硬编码的生成器函数?

在第一个示例中,您调用了创建生成器的方法:

$this->generator = $this->getValueGenerator();

第二个你没有调用它,所以它只是一个闭包:

$this->generator = function() {
    yield from [1,1,2,3,5,8,13,21];
};

调用该闭包应该创建生成器(PHP 7 如果您不想分配中间变量):

$this->generator = (function() {
    yield from [1,1,2,3,5,8,13,21];
})();