Detailed introduction to php generator
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 |
|
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:
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;
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 |
|
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 = (yield $key => $value);, otherwise a compilation error will occur. PHP7 does not need to care about this.
1
<br/>
Copy after login
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 |
|
yield from以方便我们编写比较清晰生成器嵌套,这点可以类比于函数中的嵌套调用,当函数A中调用另一个函数B,此时会等B执行完成并返回,方才继续执行。在没有yield from的时候,实现生成器嵌套需要自己实现栈并进行压栈和弹出操作以达到相同效果,那是多么痛苦的操作。
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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,

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.

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