Recommended: "PHP Video Tutorial"
What is Generator
Starting from PHP 5.5, PHP has added a new feature, that isGenerator , translated into Chinese as Generator. Generators can be simply used to implement object iteration. Let's start with a small official example.
xrange
In PHP, we all know that there is a function called range, which is used to generate an array of arithmetic sequences, and then we can use this array to perform Iteration of foreach. Specifically, this is what I want to do.
foreach (range(1, 100, 2) as $num) {
echo $num . PHP_EOL;
}
This code will output an arithmetic sequence with the first term being 1, the last term being 100, and the tolerance being 2. Its execution sequence is as follows. First, range(1, 100, 2) will generate an array, which stores an arithmetic sequence as above, and then iterate the array in foreach.
So, a question arises, what if I want to generate 1 million numbers? Then we will occupy hundreds of megabytes of memory. Although memory is very cheap now, we can't waste memory like this. Then at this time, our generator can come in handy. Consider the following code.
function xrange($start, $limit, $step = 1) {
while ($start <p>The result of this code is exactly the same as the previous code, but its internal principle is turned upside down. </p><p>We just said that in the previous code, <code>range</code> will generate an array, and then <code>foreach</code> will iterate the array to take out a certain value. But in this code, we redefined a <code>xrange</code> function. In the function, we used the keyword <code>yield</code>. We all know that when defining a function and hoping it will return a value, use <code>return</code> to return it. So this <code>yield</code> can also return a value, but it is completely different from <code>return</code>. </p><p>Using the <code>yield</code> keyword can interrupt the function while it is running, and at the same time save the context of the entire function and return an object of type <code>Generator</code>. When executing the object's <code>next</code> method, the context at the time of interruption will be reloaded and continue running until the next <code>yield</code> appears. If no <code>yield</code> appears later, , then the entire generator is considered finished. </p><p>In this way, our function call above can be written equivalently like this. </p><pre class="brush:php;toolbar:false">$nums = xrange(1, 100, 2);
while ($nums->valid()) {
echo $nums->current() . "\n";
$nums->next();
}Here, $num is an object of Generator. We see three methods here, valid, current, and next. When our function is executed and there is no yield interrupt later, then our function in xrange is completed, and the valid method will become false . As for current, it will return the value behind the current yield. This means that the generator function will be interrupted. Then after calling the next method, the function will continue to execute until the next yield appears or the function ends.
Okay, so far, we have seen that yield is used to "generate" a value and return it. In fact, yield can also be written like this $ret = yield;. Like the return value, here a value is passed into the function when continuing to execute the function. It can be used through Generator::send($value). For example.
function sum()
{
$ret = yield;
echo $ret . PHP_EOL;
}
$sum = sum();
$sum->send('I am from outside.');In this way, the program will print out the string passed in by the send method. There can be calls on both sides of yield at the same time.
function xrange($start, $limit, $step = 1) {
while ($start valid()) {
echo $nums->current() . "\n";
$nums->send($nums->current() + 1);
}For use like this, send() can return the return of the next yield.
Other Generator methods
Generator::key()
For yield, we can use yield $id => $value, this is, we can get $id through the key method, and the current method returns $value.
Generator::rewind()
This method can help us restart the execution of the generator and save the context. At the same time, it will return the first yield return Content. When the send method is executed for the first time, rewind will be called implicitly.
Generator::throw()
This method throws an exception to the generator.
Postscript
yield As a new feature of PHP 5.5, we use a new method to iterate data efficiently. At the same time, we can also use yield to implement coroutines.
The above is the detailed content of Take you to understand Generator in PHP. For more information, please follow other related articles on the PHP Chinese website!
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP 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.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP 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: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP 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.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP 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.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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.







