官术网_书友最值得收藏!

Generator delegation

As functions can call each other, similarly a generator can also delegate to another generator. Here is how a generator delegates:

<?php
function gen()
{
yield "yield 1 from gen1";
yield "yield 2 from gen1";
yield from gen2();
}

function gen2()
{
yield "yield 1 from gen2";
yield "yield 2 from gen2";
}

foreach (gen() as $val)
{
echo $val, PHP_EOL;
}


/* above will result in output:
yield 1 from gen1
yield 2 from gen1
yield 1 from gen2
yield 2 from gen2
*/

Here, gen2() is another generator being called in gen(), so a third yield in gen(), that is yield from gen2();, will transfer control to gen2(). So with that, it will start using yield from gen2().

Note that yield from is only usable with arrays, traversable, or generators. Using another function (not generator) in yield from will result in a fatal error.
You can just consider it to be similar to how we can call a function in another function.
主站蜘蛛池模板: 柏乡县| 桦甸市| 海林市| 苗栗市| 建瓯市| 天柱县| 新绛县| 平泉县| 香河县| 桦甸市| 赣榆县| 罗田县| 隆昌县| 普格县| 乌苏市| 邯郸市| 桓仁| 宜兰县| 营山县| 叙永县| 错那县| 开平市| 德惠市| 和田县| 嘉鱼县| 通榆县| 永安市| 集安市| 英德市| 东港市| 景泰县| 开阳县| 阿荣旗| 宁远县| 昌黎县| 绥宁县| 紫阳县| 交城县| 宝应县| 墨脱县| 通州区|