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

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.
主站蜘蛛池模板: 荣成市| 巩留县| 五大连池市| 兴海县| 葵青区| 马山县| 东明县| 彩票| 来凤县| 沂水县| 绵竹市| 永济市| 郎溪县| 拉萨市| 油尖旺区| 泰来县| 文昌市| 临潭县| 当涂县| 罗田县| 墨竹工卡县| 交城县| 肇庆市| 威远县| 垣曲县| 石家庄市| 固镇县| 东港市| 韶关市| 浮山县| 沙河市| 东光县| 遵义市| 宝丰县| 临泉县| 富宁县| 宁夏| 东乡族自治县| 于都县| 乌兰察布市| 高清|