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 "; }
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:
Generator implements Iterator { /** * 返回当前产生的值(yield后面表达式的值) */ public mixed current ( void ) /** * yield的键(yield 'key'=>'val';) */ 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 ) }
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)
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/>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:
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
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!

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

The session ID should be regenerated regularly at login, before sensitive operations, and every 30 minutes. 1. Regenerate the session ID when logging in to prevent session fixed attacks. 2. Regenerate before sensitive operations to improve safety. 3. Regular regeneration reduces long-term utilization risks, but the user experience needs to be weighed.

Setting session cookie parameters in PHP can be achieved through the session_set_cookie_params() function. 1) Use this function to set parameters, such as expiration time, path, domain name, security flag, etc.; 2) Call session_start() to make the parameters take effect; 3) Dynamically adjust parameters according to needs, such as user login status; 4) Pay attention to setting secure and httponly flags to improve security.

The main purpose of using sessions in PHP is to maintain the status of the user between different pages. 1) The session is started through the session_start() function, creating a unique session ID and storing it in the user cookie. 2) Session data is saved on the server, allowing data to be passed between different requests, such as login status and shopping cart content.

How to share a session between subdomains? Implemented by setting session cookies for common domain names. 1. Set the domain of the session cookie to .example.com on the server side. 2. Choose the appropriate session storage method, such as memory, database or distributed cache. 3. Pass the session ID through cookies, and the server retrieves and updates the session data based on the ID.


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software