0
0
PHPprogramming~30 mins

Yield from delegation in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Yield from delegation
📖 Scenario: Imagine you are organizing a music playlist. You have different smaller playlists for genres like rock and jazz. You want to create one big playlist that plays all songs from these smaller playlists in order.
🎯 Goal: Build a PHP generator that uses yield from to combine multiple smaller playlists into one big playlist.
📋 What You'll Learn
Create two generators for small playlists with exact song names
Create a main generator that uses yield from to delegate to the smaller playlists
Iterate over the main generator to print all songs in order
💡 Why This Matters
🌍 Real World
Combining multiple data sources or streams into one sequence is common in music apps, data processing, and event handling.
💼 Career
Understanding generators and delegation helps write efficient code for handling large data or asynchronous tasks in PHP development.
Progress0 / 4 steps
1
Create the first playlist generator
Write a generator function called rockPlaylist that yields these exact songs in order: 'Bohemian Rhapsody', 'Stairway to Heaven', 'Hotel California'.
PHP
Need a hint?

Use yield inside the function to return each song one by one.

2
Create the second playlist generator
Write a generator function called jazzPlaylist that yields these exact songs in order: 'So What', 'Take Five', 'Blue in Green'.
PHP
Need a hint?

Similar to the first playlist, use yield for each jazz song.

3
Create the main playlist generator using yield from
Write a generator function called mainPlaylist that uses yield from to delegate to rockPlaylist() first, then to jazzPlaylist().
PHP
Need a hint?

Use yield from to include all songs from each smaller playlist.

4
Print all songs from the main playlist
Use a foreach loop to iterate over mainPlaylist() and print each song on its own line using echo.
PHP
Need a hint?

Use foreach (mainPlaylist() as $song) and echo $song . "\n"; to print each song.