Home > Backend Development > PHP Tutorial > Detailed introduction to php generator

Detailed introduction to php generator

小云云
Release: 2023-03-20 20:08:02
Original
2827 people have browsed it

First, let’s take a look at how it is introduced in the PHP official documentation: Generators provide an easier way to implement simple object iteration. Compared with the way of defining a class to implement the Iterator interface, the performance overhead and complexity are Greatly reduced.

After reading this sentence, we can get several keywords: object iteration, Iterator interface, performance overhead, relatively abstract, talk is cheap show me the code, let’s start with the most classic example of a generator let's start.

The range() function in PHP will create an array containing the specified range unit in the memory and return it when used. Generally speaking, there is nothing wrong with this, but when the passed limit parameter is entered When it is very large, it means that the array that will be created in the memory will also be very large. This is too scary. This is the rhythm of bursting the memory. At this point we can use the generator to implement a more efficient range function (the following code is a simplified version of the official PHP documentation):

function xrange($start, $limit, $step = 1)
{
    //校验参数,此处省略

    for ($i = $start; $i <= $limit; $i += $step) {
        //向外产出值
        yield $i;
    }
}

//xrange此时返回的是一个生成器对象
$gen = xrange(1, 9);

//对生成器进行迭代
foreach ($gen as $number) {
    echo "$number ";
}
Copy after login

The xrange and range functions have the same effect here. An iterable variable is generated, but the difference is that the range function is a bit like what is often called "preloading" in ORM, while xrange is "lazy loading" and only waits until the iteration reaches that point to generate the corresponding value, so xrange does not need Allocating large blocks of memory to store variables greatly saves memory and improves efficiency.

Now let’s summarize the similarities and differences between generators and ordinary functions:

  1. The generator must contain the yield keyword (used to generate results), and it can be Appears many times. In ordinary functions, return can only be used to return results to the outside, and the function has been executed;

  2. A generator cannot return a value through return. Doing so will generate a compilation error. PHP Fatal error: Generators cannot return values ​​using "return" (Note: This will not go wrong under PHP7, but it will terminate the generator and continue execution. That is, calling the valid() method will return false. However, in PHP5, return empty is a valid syntax and it will terminate the generator and continue execution)

Generator class (Generator)

Generator object is returned from the generator, $gen in the above code It's just a generator object. Note that the generator object is different from objects of other classes. It cannot be created through the new keyword and can only be obtained from the generator function. First, let’s take a look at the Generator class summary to see its composition:

Generator implements Iterator
{
    /**
     * 返回当前产生的值(yield后面表达式的值)
     */
    public mixed current ( void )

    /**
     * yield的键(yield &#39;key&#39;=>&#39;val&#39;;)
     */
    public mixed key ( void )

    /**
     * 从上一个yield之后继续执行,直到下一个yield
     */
    public void next ( void )

    /**
     * 重置迭代器(对于生成器并没什么卵用)
     */
    public void rewind ( void )

    /**
     * 向生成器中传入一个值,并从上一个yield之后继续执行
     */
    public mixed send ( mixed $value )

    /**
     * 向生成器中抛出一个异常,并从上一个yield之后继续执行
     */
    public void throw ( Exception $exception )

    /**
     * 检查迭代器是否被关闭(false表示已关闭)
     */
    public bool valid ( void )

    /**
     * 序列化回调,但是生成器不能被序列化,因此会抛出一个异常
     */
    public void __wakeup ( void )
}
Copy after login

As can be seen from the above class summary, the Generator class implements the Iterator interface, so it has the characteristics of an iterator. In addition, it adds send(), throw() and __wekeup() methods. The relevant method descriptions have been commented and will not be repeated here.

I wrote a lot, but I found that my writing is not good, so I might as well draw a picture to get a feel for it (the pictures are not beautiful either, so please just make do with it, 2333) <br/>

yield Keyword

Next let’s take a look at the yield keyword. Its simplest calling form looks like the return of an ordinary function. The difference is that ordinary return will return a value and terminate the execution of the function, while yield will Returns a value to the code that loops through this generator and simply pauses execution of the generator function.

This is a typical yield expression: $data = yield $key => $value;. This expression includes two parts:

Note: PHP5 requires parentheses $data = (yiel
<br/>
Copy after login
d $key => $value);, otherwise a compilation error will occur. PHP7 does not need to care about this.
  • First, it is the expression after yield, this can It can be a single value or a key-value pair, corresponding to an element in the array. This part of the expression is returned to the upper layer, that is, the upper layer can receive the value through the current method or the return value of the send method;

  • The other piece is the yield keyword itself. I personally understand it as a receiver, which will receive the value passed in by the send method. This value is the current value of the entire yield expression and can be The variable on the left receives.

This may be a bit abstract, but let’s look at the picture above: <br/>

Generator delegate (yield from)

PHP7 has added yield From keyword, this syntax allows yield values ​​from other generators, Traversable objects, or arrays through the yield from generation function. The various characteristics of yield from are the same as yield, which generates data, but the expressions that follow are different. Let’s look at an example (excerpted from PHP official documentation):

function count_to_ten()
{
    yield 1;
    yield 2;
    yield from [3, 4];  //生成数组
    yield from new ArrayIterator([5, 6]);   //生成可遍历对象
    yield from seven_eight();   //生成生成器对象
    yield 9;
    yield 10;
}

function seven_eight()
{
    yield 7;
    yield from eight();
}

function eight()
{
    yield 8;
}

foreach (count_to_ten() as $num) {
    echo "$num ";
}

//输出:1 2 3 4 5 6 7 8 9 10
Copy after login

yield from以方便我们编写比较清晰生成器嵌套,这点可以类比于函数中的嵌套调用,当函数A中调用另一个函数B,此时会等B执行完成并返回,方才继续执行。在没有yield from的时候,实现生成器嵌套需要自己实现栈并进行压栈和弹出操作以达到相同效果,那是多么痛苦的操作。

相关推荐:

php生成器简介和示例

php生成器对象

PHP生成器简单实例,php生成器_PHP教程

The above is the detailed content of Detailed introduction to php generator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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