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

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.
主站蜘蛛池模板: 陆丰市| 邳州市| 绥芬河市| 宜春市| 上饶县| 绩溪县| 抚松县| 平舆县| 广水市| 新乡市| 九江县| 土默特左旗| 江西省| 汽车| 古蔺县| 陆川县| 浮山县| 体育| 武穴市| 朝阳区| 白朗县| 临安市| 江西省| 六安市| 东辽县| 巫溪县| 武乡县| 乐安县| 高青县| 金昌市| 南开区| 哈尔滨市| 德兴市| 进贤县| 襄城县| 古浪县| 阳曲县| 临江市| 阿拉善左旗| 儋州市| 中江县|