我创建一个使用发电机来返回值时,一个特定的方法被称为类,喜欢的东西:当发电机被定义为哪个好作品完美发电机不能在一个封闭
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()
任何人都可以解释为什么我不能把发电机这样的实际逻辑
?以及我如何能够使用闭包而不是硬编码的生成器函数?
您将该字段初始化为闭包,但您希望调用闭包的结果。 – localheinz