Computer >> Computer tutorials >  >> Programming >> PHP

Generator delegation in PHP 7


The concept of generator is not new to PHP 7, because it was available in the earlier versions too. With generators, implementation becomes easy without the overhead of implementing a class that implements the iterator interface. With the help of a generator, we can write foreach code without using an array in memory. It also helps to eliminate the “exceed memory limit errors”.

With the help of generator delegation in PHP 7, we can delegate to another generator automatically. It also allows arrays and objects that implement the traversable interface.

Generator delegation Example 1

<html>
<head>
<title> PHP 7 : Tutorialpoint </title>
</head>
<body>
<?php
   function generator(){
      yield "zero";
      yield "one";
      yield "two";
   }
   function generator1(){
      yield "three";
      yield "four";
      yield "five";
   }
   function generator2(){
      yield "six";
      yield "seven";
      yield "eight";
      yield from generator();
      yield "nine";
      yield from generator1();
      yield "ten";
   }
   foreach (generator() as $value){
      echo $value, PHP_EOL;
   }
   foreach(generator2() as $value){
      echo $value, PHP_EOL;
   }
?>
</body>
</html>

Output

The output for the above PHP program generator delegation program will be −

zero one two six seven eight zero one two nine three four five ten

Explanation

  • 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 injects the actual PHP 7 code for generator return expression.
  • Secondly, three functions are declared using “generator”, “generator1”, and “generator2”.
  • We defined the yield “zero”, “one”, and “two” in the generator function.
  • In the “generator1” function, yield “three”, “four”, and “five” have been defined.
  • In the ‘generator2’ function, we have defined yield”six”, “seven”, and “eight” read the generator and generator 1 in generator2.
  • Finally, we are iterating on the “generator” and “generator2” function till the end of echoing the values of the yields.