Understanding Generators in PHP

What is PHP Generators ?

As per the php wiki “A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.”

so what that means?
In general,  generators  functions allow you to declare a function that behaves like an iterator by yielding value and saving its state so that when its called again; iteration can continue. This is very helpful to save memory  when iterating large data set.

Example:

Lets take a example of simple range iteration:

function my_range($start,$end)  {
    $out = [];
    for($i=$start; $i<=$end; $i++) {
        $out[] = $i;
    }
    return $out;
}

foreach( y_range(0,1000) as $j) {
//logic here
}

 In this example, my_range() function will store every output in array, since the array is big we need more memory to store. So if the range set is too high, most probably we will run out of memory. 

Lets do same thing  with Generators:

function my_range($start,$end)  {
       for($i=$start; $i<=$end; $i++) {
           yield $i;
       }
}

foreach( y_range(0,1000) as $j) {
//logic here
}

In above example, each time foreach is run only one value is return, and state (instance) is saved in “yield” so next time it will call next() and continue. This way each time we just need integer memory space each time that will save lots of memory and also results in performance.

Injection:
Apart from getting value we can also pass value to generators

Eample:

function my_range($start,$end)  {
       for($i=$start; $i<=$end; $i++) {
       $command = (yield $i); 
       if($command =='terminate')
           return;
       }
}
$iterator = y_range(0,1000);
foreach($iterator as $j) { //logic here
    if(//condition) {
        $iterator->send('terminate');

}
}

send function is use to send command back to generator.

Additional functions:

Since generators implements iterator interface class we can use additional functions:

current ( void )
 scalar key ( void )
 void next ( void )
 void rewind ( void )
 boolean valid
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s