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):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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

1

<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):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

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 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
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

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 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.

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

See all articles