【问题标题】:PHP generator return typePHP 生成器返回类型
【发布时间】:2019-07-03 08:52:21
【问题描述】:

我以前从未在 PHP 中使用过生成器,documentation 中没有显示返回类型声明的示例。

在 PhpStorm 中,当我这样做时,IDE 中出现错误:

public function getDataIncrementally(): void {
    yield from [/* some large set of numbers*/];
}

错误是:

生成器只能声明返回类型为 Generator、Iterator 或 Traversable,或者 iterable,不允许使用 void。

我可以看到继承树是Traversable -> Iterator -> Generator。同时,iterable 是 PHP 7.1 中引入的新伪类型。

如果我只需要支持 PHP >= 7.1,是否适合使用 iterable 作为返回类型声明?

【问题讨论】:

    标签: php iterator generator iterable php-generators


    【解决方案1】:

    您的返回类型是Generator,但您使用的是void。请尝试以下操作:

    public function getDataIncrementally(): \Generator {
        yield from [/* some large set of numbers*/];
    }
    

    【讨论】:

    • 推荐Generator 优于iterable?这是我真正希望得到答案的问题
    • @rink.attendant.6 不,Generator 是更准确的数据类型,iterable 更宽,因为您还可以使用IteratorGeneratorTraversable 作为返回输入
    • 如果你希望你的界面同时支持ArrayIteratorGenerator,你应该使用iterable。最好是Interface
    猜你喜欢
    • 2021-07-11
    • 2011-07-03
    • 1970-01-01
    • 2017-11-09
    • 2017-03-05
    • 1970-01-01
    • 2016-06-27
    • 2013-05-22
    相关资源
    最近更新 更多