Generator Return Expressions in PHP 7


In the previous versions of PHP, generator functions were not able to return expressions, but from the PHP 5.5, generator return expression is added in the existing one. By using generator return expressions, it is easy to use the return statement within a generator and, it also returns the value of the final expression.

  • By using the generator return expression, we can only return the value of the expression but cannot return the reference. By using the new Generator::getReturn() method, we can fetch the value which can be used once the generator function has finished yielding the defined values.
  • Using PHP 7 generator, we can return a final value from generator return expressions. We can retrieve the return expression by using $generator>getReturn() because PHP 7 allows for a final value to be returned by a generator from co-routine counting in the program that could hold by the client code executing the generator.

Generator Return Expressions: Example 1

Live Demo

<html>
<head>
<title> PHP 7 Feature : Generator Return Expressions </title>
</head>
<body>
<?php
   $generator = (function(){
      yield "five";
      yield "six";
      yield "seven";
      return "eight";
   })
   ();
   foreach ($generator as $val){
      echo $val, PHP_EOL;
   }
   echo $generator ->getReturn(), PHP_EOL;
?>
</body>
</html>

Output

The output for the above PHP program will be:

five six seven eight

Explanation for the above PHP 7 program −

  • We can write the above code in an editor and can write the required HTML code as given in the above example and the body part of HTML inject the actual PHP 7 code for generator return expression.
  • Secondly, a function having a reference as $generator is declared.
  • In reference to $generator, we defined yield “five”,” six”,” seven”, and “eight”.
  • Finally, we iterating on the “$generator” function till the end (PHP_EOL) and echoing the values of the yields along with the generator return expression.

Generator Return Expressions: Example 2

Live Demo

<html>
<head>
<title> PHP 7 Feature: Generator Return Expressions Example </title>
</head>
<body>
<?php
   function gen(){
      yield 'A';
      yield 'B';
      yield 'C';
      return 'gen-return';
   }
   $generator = gen();
   var_dump($generator);
   foreach ($generator as $letter){
      echo $letter;
   }
   var_dump($generator->getReturn());
?>
</body>
</html>

Output

The output for the above PHP program will be −

object(Generator)#1 (0) { }ABCstring(10) "gen-return"

Updated on: 13-Mar-2021

247 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements