- 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.
推薦閱讀
- AngularJS Testing Cookbook
- Linux C/C++服務器開發實踐
- Programming ArcGIS 10.1 with Python Cookbook
- PhpStorm Cookbook
- .NET 3.5編程
- RSpec Essentials
- SQL Server與JSP動態網站開發
- Learning Continuous Integration with TeamCity
- Hands-On GUI Programming with C++ and Qt5
- UML2面向對象分析與設計(第2版)
- Python青少年趣味編程
- C++程序設計教程(第2版)
- 深入理解BootLoader
- Arduino電子設計實戰指南:零基礎篇
- Visual C++程序設計與項目實踐