0
0
PHPprogramming~30 mins

Generator return values in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Generator Return Values in PHP
📖 Scenario: Imagine you are managing a list of tasks for a small project. You want to process each task one by one but also get a final summary message when all tasks are done.
🎯 Goal: You will create a PHP generator that yields tasks one by one and then returns a final message. You will learn how to get this return value from the generator.
📋 What You'll Learn
Create a generator function that yields tasks
Use a variable to store the final return message
Iterate over the generator using a foreach loop
Capture and display the generator's return value
💡 Why This Matters
🌍 Real World
Generators help process large or unknown amounts of data step-by-step without loading everything into memory. The return value can summarize the process.
💼 Career
Understanding generators and their return values is useful for PHP developers working on efficient data processing, asynchronous tasks, or pipelines.
Progress0 / 4 steps
1
Create a generator function with tasks
Write a generator function called taskGenerator that yields these exact tasks as strings: 'Setup environment', 'Write code', 'Test code'.
PHP
Need a hint?

Use the yield keyword inside the function to return each task one by one.

2
Add a return statement with a final message
Inside the taskGenerator function, after yielding all tasks, add a return statement that returns the string 'All tasks completed'.
PHP
Need a hint?

Use return 'All tasks completed'; after the last yield.

3
Iterate over the generator and capture the return value
Create a variable called $generator and assign it the result of calling taskGenerator(). Then use a foreach loop with $task to iterate over $generator and print each task with echo. After the loop, get the return value from $generator using $generator->getReturn() and store it in a variable called $finalMessage.
PHP
Need a hint?

Use foreach ($generator as $task) to loop and $generator->getReturn() to get the final message.

4
Print the final return message
Write a line to print the $finalMessage variable using echo.
PHP
Need a hint?

Use echo $finalMessage . "\n"; to print the message on a new line.