生成器不能处于关闭状态

Mar*_*ker 2 php closures generator anonymous-function

我正在创建一个类,它使用生成器在调用特定方法时返回值,如:

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();
}
Run Code Online (Sandbox Code Playgroud)

当生成器被定义为类本身内的方法时,哪种方法非常有效....但我想让它更具动态性,并使用闭包作为生成器,如:

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

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

致命错误:未捕获错误:调用未定义方法Closure :: valid()

在打电话给 getValue()

任何人都可以解释为什么我不能用这种方式调用发生器的实际逻辑?我怎么能够使用闭包而不是硬编码的生成器函数?

Cia*_*lty 7

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

$this->generator = $this->getValueGenerator();
Run Code Online (Sandbox Code Playgroud)

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

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

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

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