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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

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,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles