Home > Backend Development > PHP Tutorial > Take you to understand Generator in PHP

Take you to understand Generator in PHP

藏色散人
Release: 2023-04-09 16:42:02
forward
3724 people have browsed it

Recommended: "PHP Video Tutorial"

What is Generator

Starting from PHP 5.5, PHP has added a new feature, that isGenerator , translated into Chinese as Generator. Generators can be simply used to implement object iteration. Let's start with a small official example.

xrange

In PHP, we all know that there is a function called range, which is used to generate an array of arithmetic sequences, and then we can use this array to perform Iteration of foreach. Specifically, this is what I want to do.

foreach (range(1, 100, 2) as $num) {
    echo $num . PHP_EOL;
}
Copy after login

This code will output an arithmetic sequence with the first term being 1, the last term being 100, and the tolerance being 2. Its execution sequence is as follows. First, range(1, 100, 2) will generate an array, which stores an arithmetic sequence as above, and then iterate the array in foreach.

So, a question arises, what if I want to generate 1 million numbers? Then we will occupy hundreds of megabytes of memory. Although memory is very cheap now, we can't waste memory like this. Then at this time, our generator can come in handy. Consider the following code.

function xrange($start, $limit, $step = 1) {
    while ($start <= $limit) {
        yield $start;
        $start += $step;
    }
}

foreach (xrange(1, 100, 2) as $num) {
    echo $num . PHP_EOL;
}
Copy after login

The result of this code is exactly the same as the previous code, but its internal principle is turned upside down.

We just said that in the previous code, range will generate an array, and then foreach will iterate the array to take out a certain value. But in this code, we redefined a xrange function. In the function, we used the keyword yield. We all know that when defining a function and hoping it will return a value, use return to return it. So this yield can also return a value, but it is completely different from return.

Using the yield keyword can interrupt the function while it is running, and at the same time save the context of the entire function and return an object of type Generator. When executing the object's next method, the context at the time of interruption will be reloaded and continue running until the next yield appears. If no yield appears later, , then the entire generator is considered finished.

In this way, our function call above can be written equivalently like this.

$nums = xrange(1, 100, 2);
while ($nums->valid()) {
    echo $nums->current() . "\n";
    $nums->next();
}
Copy after login

Here, $num is an object of Generator. We see three methods here, valid, current, and next. When our function is executed and there is no yield interrupt later, then our function in xrange is completed, and the valid method will become false . As for current, it will return the value behind the current yield. This means that the generator function will be interrupted. Then after calling the next method, the function will continue to execute until the next yield appears or the function ends.

Okay, so far, we have seen that yield is used to "generate" a value and return it. In fact, yield can also be written like this $ret = yield;. Like the return value, here a value is passed into the function when continuing to execute the function. It can be used through Generator::send($value). For example.

function sum()
{
    $ret = yield;
    echo $ret . PHP_EOL;
}

$sum = sum();
$sum->send('I am from outside.');
Copy after login

In this way, the program will print out the string passed in by the send method. There can be calls on both sides of yield at the same time.

function xrange($start, $limit, $step = 1) {
    while ($start <= $limit) {
        $ret = yield $start;
        $start += $step;
        echo $ret . PHP_EOL;
    }
}

$nums = xrange(1, 100, 2);
while ($nums->valid()) {
    echo $nums->current() . "\n";
    $nums->send($nums->current() + 1);
}
Copy after login

For use like this, send() can return the return of the next yield.

Other Generator methods

Generator::key()

For yield, we can use yield $id => $value, this is, we can get $id through the key method, and the current method returns $value.

Generator::rewind()

This method can help us restart the execution of the generator and save the context. At the same time, it will return the first yield return Content. When the send method is executed for the first time, rewind will be called implicitly.

Generator::throw()

This method throws an exception to the generator.

Postscript

yield As a new feature of PHP 5.5, we use a new method to iterate data efficiently. At the same time, we can also use yield to implement coroutines.

The above is the detailed content of Take you to understand Generator in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template