- Building RESTful Web Services with PHP 7
- Haafiz Waheed ud din Ahmad
- 166字
- 2021-07-03 00:02:23
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.
You can just consider it to be similar to how we can call a function in another function.
推薦閱讀
- Reporting with Visual Studio and Crystal Reports
- OpenShift開發指南(原書第2版)
- Computer Vision for the Web
- 垃圾回收的算法與實現
- SQL Server 2012數據庫技術及應用(微課版·第5版)
- Building a RESTful Web Service with Spring
- 算法訓練營:入門篇(全彩版)
- 數據庫系統原理及MySQL應用教程
- 老“碼”識途
- Amazon S3 Cookbook
- Linux C編程:一站式學習
- SQL Server實用教程(SQL Server 2008版)
- 深入剖析Java虛擬機:源碼剖析與實例詳解(基礎卷)
- INSTANT Adobe Edge Inspect Starter
- Python Machine Learning Blueprints:Intuitive data projects you can relate to