Sunday 9 December 2018

Generator

Generator


function read($file)
{
    $fp = fopen($file, 'rb');

    while(($line = fgets($fp)) !== false)
        yield rtrim($line, "\r\n");

    fclose($fp);
}

// Usage
foreach(read('http://example.com') as $line)
{
    var_dump($line);
}

The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate. Instead, you can write a generator function, which is the same as a normal function, except that instead of returning once, a generator can yield as many times as it needs to in order to provide the values to be iterated over.
Sources
Stack Overflow Geek Tality

No comments:

Post a Comment