2017-07-02 57 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

我已经修改了答案以使括号正确 –