REMEMBER PHP

MINTE9
2REMEMBER




Last update:   23-07-2021

Yield values

A generator function looks like a normal function, except of returning a value. It yields as many values as it needs to.
 
function myGenerator()
{
    for ($i=1; $i<=3; $i++) {
        yield $i;
    }
}
... 3 more rows
˄˄˄
Generator class is implementing Iterator interface. You have to loop over to get values.
 RunCode
function myGenerator()
{
    for ($i=1; $i<=3; $i++) {
        yield $i;
    }
}

foreach (myGenerator() as $v) {
    echo $v . PHP_EOL;
}

// Outputs: 1 2 3

... 7 more rows
˄˄˄
Yield doesn't stop the execution of the function and returning, Yield provides a value and pause the execution of the function.

Examples

This is an example without generator (bad).
 RunCode
// bad example

function makeRange($length)
{
    $data = array();

    $i = 0;
    while( $i++ < $length) $data[] = $i;

    echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. "<br>";

    return $data;
}

foreach(makeRange(1000000) as $v) {} // 32.38 MB

foreach(makeRange(3000000) as $v) {} // Allowed memory exhausted
... 8 more rows
˄˄˄
This is how generators save memory (good).
 RunCode
// yield example

function makeRange($length)
{
    $i = 0;
    while( $i++ < $length) yield $i;

    echo round(memory_get_usage() / 1024 / 1024, 2) . ' MB'. "<br>";
}

foreach(makeRange(1000000) as $v) {} // 0.37 MB

foreach(makeRange(3000000) as $v) {} // 0.37 MB
... 6 more rows
˄˄˄
Big files example,
 
function makeFile() {

    if ($fd = fopen("generators.txt", "w+")) {

        $i = 0;
        while($i++ < 10000000) { // 128 MB allowed in php
            fwrite($fd, $i . " GGG <br>");
        }

        fclose($fd);
    }
}

//makeFile(); // 152 MB generators.txt

function getRows() {

    if ($fd = fopen("generators.txt", "rb")) {

        while (!feof($fd)) {
            yield fgets($fd, 4096);
        }
    }
}

function getRowsArray() {

    $data = array();

    if ($fd = fopen("generators.txt", "rb")) {

        while (!feof($fd)) {
            $data[] = fgets($fd, 4096);
        }
    }

    return $data;
}

// yield
foreach(getRows() as $v) {} echo "it works with yield";

// array
foreach(getRowsArray() as $v) {}
    // Allowed memory size of 134217728 bytes exhausted
... 28 more rows
˄˄˄

Questions    
No. 82   Dependency Injection
CARD
81
96

        A B C D E F
🔔
1/1