2017-07-02 59 views
2

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

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()

任何人都可以解釋爲什麼我不能把發電機這樣的實際邏輯

?以及我如何能夠使用閉包而不是硬編碼的生成器函數?

+1

您將該字段初始化爲閉包,但您希望調用閉包的結果。 – localheinz

回答

5

在調用該方法的第一個例子,創造了發電機:

$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]; 
})(); 
+0

賓果!雖然PHP7「方法」似乎不起作用(即使使用額外的大括號),但使用中間變量以便閉包是可調用的。謝謝! –

+0

啊! gt括號現在正在工作 –

+0

我已經修改了答案以使括號正確 –