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];
    })();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源