我創建一個使用發電機來返回值時,一個特定的方法被稱爲類,喜歡的東西:當發電機被定義爲哪個好作品完美發電機不能在一個封閉
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