Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Generator Return Expressions in PHP 7
In PHP 7, generator functions can now return expressions using the return statement. This enhancement allows generators to yield values during iteration and then return a final value when the generator completes execution.
Key Features
Generator return expressions in PHP 7 provide the following capabilities −
- Return a final value from a generator function after all yields are completed
- Retrieve the returned value using the
Generator::getReturn()method - Only expression values can be returned, not references
- The return value is accessible once the generator has finished yielding all values
Basic Example
Here's a simple example demonstrating generator return expressions −
<?php
$generator = (function(){
yield "five";
yield "six";
yield "seven";
return "eight";
})();
foreach ($generator as $val) {
echo $val . "<br>";
}
echo "Return value: " . $generator->getReturn() . "<br>";
?>
five six seven Return value: eight
Named Generator Function
You can also use named generator functions with return expressions −
<?php
function gen() {
yield 'A';
yield 'B';
yield 'C';
return 'gen-return';
}
$generator = gen();
foreach ($generator as $letter) {
echo $letter . " ";
}
echo "\nGenerator return: " . $generator->getReturn();
?>
A B C Generator return: gen-return
Important Notes
- The
getReturn()method can only be called after the generator has finished execution - Calling
getReturn()before the generator completes will throw an exception - Generator return expressions work with any data type − strings, arrays, objects, etc.
Conclusion
Generator return expressions in PHP 7 enhance the functionality of generators by allowing them to return a final value. This feature is particularly useful for aggregating results or providing status information after processing all yielded values.
Advertisements
