- 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.
推薦閱讀
- Three.js開發指南:基于WebGL和HTML5在網頁上渲染3D圖形和動畫(原書第3版)
- AIRAndroid應用開發實戰
- RTC程序設計:實時音視頻權威指南
- 運用后端技術處理業務邏輯(藍橋杯軟件大賽培訓教材-Java方向)
- MySQL從入門到精通(軟件開發視頻大講堂)
- Getting Started with React Native
- Visual Basic程序設計基礎
- Instant GLEW
- 深入理解Kafka:核心設計與實踐原理
- 零基礎學編程系列(全5冊)
- Microsoft Dynamics GP 2013 Cookbook
- 劍指大數據:企業級電商數據倉庫項目實戰(精華版)
- C語言程序設計
- Expert Angular
- 軟件開發踐行錄:ThoughtWorks中國區文集