dtf54486 2017-07-02 10:44
浏览 49
已采纳

生成器不能处于关闭状态

I'm creating a class that uses a generator to return values when a particular method is called, something like:

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

Which works perfectly well when the generator is defined as a method within the class itself.... but I want to make this more dynamic, and use a closure as the generator, something like:

class test {
    public function __construct() {
        $this->generator = function() {
            yield from [1,1,2,3,5,8,13,21];
        };
    }
}

Unfortunately, when I try to run this, I get

Fatal error: Uncaught Error: Call to undefined method Closure::valid()

in the call to getValue()

Can anybody explain the actual logic of why I can't call the generator this way? And how I might be able to use a closure rather than a hard-coded generator function?

  • 写回答

1条回答 默认 最新

  • dton37910 2017-07-02 11:32
    关注

    In the first example you invoke the method, creating the generator:

    $this->generator = $this->getValueGenerator();
    

    In the second you do not invoke it, so it's merely a closure:

    $this->generator = function() {
        yield from [1,1,2,3,5,8,13,21];
    };
    

    Invoking that closure should create the generator (PHP 7 if you don't want to assign an intermediate variable):

    $this->generator = (function() {
        yield from [1,1,2,3,5,8,13,21];
    })();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?