Home Backend Development PHP Tutorial Take you through a detailed explanation of the use of PHP generator

Take you through a detailed explanation of the use of PHP generator

Dec 01, 2020 pm 01:50 PM
php generator

Learn how to use PHP generator

What is a generator?

Listening to the fancy name, it feels like a function to create something. In fact, the generator is an iterator for iteration. It provides 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.

Recommendation: "PHP Video Tutorial"

After talking for a long time, it is more intuitive to look at the code directly.

function test1()
{
    for ($i = 0; $i < 3; $i++) {
        yield $i + 1;
    }
    yield 1000;
    yield 1001;
}
foreach (test1() as $t) {
    echo $t, PHP_EOL;
}
// 1
// 2
// 3
// 1000
// 1001
Copy after login

It’s such a simple piece of code. First, the generator must be in the method and use the yield keyword; secondly, each yield can be regarded as a return; finally, when the outer loop is used, the return value of one yield is taken at a time. In this example, the loop three times returns the three numbers 1, 2, and 3. Then write two more lines of yield outside the loop to output 1000 and 1001 respectively. Therefore, the outer foreach loop outputs a total of five times.

It's amazing, it's obviously a method, why can it be looped and it's still a very strange format for returning the loop body. Let’s print this test() method directly to see what is printed:

// 是一个生成器对象
var_dump(test1());
// Generator Object
// (
// )
Copy after login

When yield is used to return content, a Generator object is returned. This object is called a generator object. It cannot be instantiated directly by new and can only be returned through the generator function. This class contains methods such as current() and key(), and the most important thing is that this class implements the Iterator interface, so it is a special iterator class.

Generator implements Iterator {
    /* 方法 */
    public current ( void ) : mixed
    public key ( void ) : mixed
    public next ( void ) : void
    public rewind ( void ) : void
    public send ( mixed $value ) : mixed
    public throw ( Exception $exception ) : void
    public valid ( void ) : bool
    public __wakeup ( void ) : void
}
Copy after login

What is the use of generator?

I’ve been working on it for a long time, isn’t it just an iterator? Why go to all this trouble? Wouldn't it be better to just use an iterator or directly return an array in the method? Yes, it's really not that troublesome under normal circumstances, but if the amount of data is particularly large, this generator can exert its powerful power. The most powerful part of the generator is that it does not require an array or any data structure to store this series of data. Each iteration is dynamically returned when the code is executed to yield. Therefore, the generator can greatly save memory.

// 内存占用测试
$start_time = microtime(true);
function test2($clear = false)
{
    $arr = [];
    if($clear){
        $arr = null;
        return;
    }
    for ($i = 0; $i < 1000000; $i++) {
        $arr[] = $i + 1;
    }
    return $arr;
}
$array = test2();
foreach ($array as $val) {
}
$end_time = microtime(true);
echo "time: ", bcsub($end_time, $start_time, 4), PHP_EOL;
echo "memory (byte): ", memory_get_usage(true), PHP_EOL;
// time: 0.0513
// memory (byte): 35655680
$start_time = microtime(true);
function test3()
{
    for ($i = 0; $i < 1000000; $i++) {
        yield $i + 1;
    }
}
$array = test3();
foreach ($array as $val) {
}
$end_time = microtime(true);
echo "time: ", bcsub($end_time, $start_time, 4), PHP_EOL;
echo "memory (byte): ", memory_get_usage(true), PHP_EOL;
// time: 0.0517
// memory (byte): 2097152
Copy after login

The above code simply obtains the result after 1,000,000 loops, but it can also be seen intuitively. The version using the generator only consumes 2M of memory, while the version without the generator consumes 35M of memory, which is more than 10 times the difference, and the larger the difference, the more obvious the difference. Therefore, some experts say that the generator is the most underestimated feature in PHP.

Applications of generators

Next, let’s take a look at some basic application methods of generators.

Returning a null value and interrupting

Of course the generator can also return a null value, just yield; without any value can return a null value. Using return; directly in a method can also be used to interrupt the continued execution of the generator. In the following code, we return a null value when $i = 4;, that is, 5 will not be output (because we return $i 1). Then when $i == 7

use return; to interrupt the continued execution of the generator, that is, the loop will only output up to 7 and end.

// 返回空值以及中断
function test4()
{
    for ($i = 0; $i < 10; $i++) {
        if ($i == 4) {
            yield; // 返回null值
        }
        if ($i == 7) {
            return; // 中断生成器执行
        }
        yield $i + 1;
    }
}
foreach (test4() as $t) {
    echo $t, PHP_EOL;
}
// 1
// 2
// 3
// 4
// 5
// 6
// 7
Copy after login

Return key-value pair form

Don’t be surprised, the generator can really return a traversable object in the form of key-value pair for use by foreach, and the syntax is very easy to remember: yield key = > value; Is it exactly the same as the definition form of array items? It is very intuitive and easy to understand.

function test5()
{
    for ($i = 0; $i < 10; $i++) {
        yield &#39;key.&#39; . $i => $i + 1;
    }
}
foreach (test5() as $k=>$t) {
    echo $k . &#39;:&#39; . $t, PHP_EOL;
}
// key.0:1
// key.1:2
// key.2:3
// key.3:4
// key.4:5
// key.5:6
// key.6:7
// key.7:8
// key.8:9
// key.9:10
Copy after login

Externally pass data

We can pass a value to the generator through the Generator::send method. The value passed in will be treated as the return value of the generator's current yield. Then we can make some judgments based on this value, such as interrupting the execution of the generator based on external conditions.

function test6()
{
    for ($i = 0; $i < 10; $i++) {
        // 正常获取循环值,当外部send过来值后,yield获取到的就是外部传来的值了
        $data = (yield $i + 1);
        if($data == &#39;stop&#39;){
            return;
        }
    }
}
$t6 = test6();
foreach($t6 as $t){
    if($t == 3){
        $t6->send(&#39;stop&#39;);
    }
    echo $t, PHP_EOL;
}
// 1
// 2
// 3
Copy after login

The above code may be confusing to understand, but just remember the line in the comment (get the loop value normally, when the value is sent from the outside, what yield gets is the value from the outside) . In addition, variables must be enclosed in parentheses to obtain the value of yield.

yield from syntax

yield from syntax actually refers to obtaining data one by one from another iterable object and forming a generator return. Just look at the code.

function test7()
{
    yield from [1, 2, 3, 4];
    yield from new ArrayIterator([5, 6]);
    yield from test1();
}
foreach (test7() as $t) {
    echo &#39;test7:&#39;, $t, PHP_EOL;
}
// test7:1
// test7:2
// test7:3
// test7:4
// test7:5
// test7:6
// test7:1
// test7:2
// test7:3
// test7:1000
Copy after login

In the test7() method, we use yield from to obtain data from an ordinary array, an iterator object, and another generator respectively and return it as the content of the current generator.

Little surprise

Can the generator use count to get the quantity?

Sorry, the generator cannot use count to get its quantity.

$c = count(test1()); // Warning: count(): Parameter must be an array or an object that implements Countable
// echo $c, PHP_EOL;
Copy after login

Using count to get the number of generators will directly report a Warning warning. Direct output will always display 1 because of the characteristics of count (forcing it into an array will display 1).

Use the generator to get the Fibonacci sequence

// 利用生成器生成斐波那契数列
function fibonacci($item)
{
    $a = 0;
    $b = 1;
    for ($i = 0; $i < $item; $i++) {
        yield $a;
        $a = $b - $a;
        $b = $a + $b;
    }
}
$fibo = fibonacci(10);
foreach ($fibo as $value) {
    echo "$value\n";
}
Copy after login

This code does not need much explanation, it is a very intuitive code.

Summarize

The generator is definitely a hidden treasure in PHP, not only for memory saving, but the syntax is actually very concise and clear. We don't need to define an additional array inside the method to store the return value, we can just yield and return one by one. It's totally worth trying in actual projects, but don't forget to share it with your friends after you try it. Most people may not have been exposed to this feature! !

Test code: https://github.com/zhangyue0503/dev-blog/blob/master/php/202002/source/Learn the use of PHP generator.php

Reference documentation: https://www.php.net/manual/zh/language.generators.overview.php https://www.php.net/manual/zh/class.generator.php

The above is the detailed content of Take you through a detailed explanation of the use of 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
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
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.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

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

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles