我正在创建一个类,它使用生成器在调用特定方法时返回值,例如:
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 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];
})();
关于php - 生成器不能处于闭包状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44869934/