Table of Contents
Generator class (Generator)
yield Keyword
Generator delegate (yield from)
Home Backend Development PHP Tutorial Detailed introduction to php generator

Detailed introduction to php generator

Mar 06, 2018 pm 01:09 PM
php introduce detailed

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles