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

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.
主站蜘蛛池模板: 娱乐| 桂平市| 甘洛县| 商洛市| 寻乌县| 天峻县| 建瓯市| 文安县| 兴山县| 静海县| 桓台县| 清新县| 巩义市| 宝山区| 红河县| 沧源| 沛县| 平潭县| 宜昌市| 祁连县| 保亭| 灌南县| 吕梁市| 新余市| 威海市| 长沙市| 抚宁县| 军事| 大石桥市| 富锦市| 古田县| 崇阳县| 土默特左旗| 股票| 昌宁县| 苍梧县| 土默特右旗| 沿河| 茂名市| 湖口县| 镇安县|