Learn how to use yield in php in one minute (share)

慕斯
Release: 2023-04-10 09:12:01
forward
7934 people have browsed it

The usage of yield in php, I believe that most people still don’t know how to use it, or even don’t know what yield is, so this article I am here to tell you some issues about yield and how to use yield to solve the problems we encounter in Php.

Problems solved by yield

Solve the bottleneck of running memory. The variables in the PHP program are stored in the memory. When reading Excel files, there will be insufficient memory and the following will appear:

Fatal Error: Allowed memory size of xxxxxx bytes
Copy after login

So the maximum running memory setting of php will be set: ini_set('memory_limit', '200M')

But when we read a file as large as 5g At that time, we may not be able to bear the running memory, so we will choose yield

First acquaintance with Yield

to run:

<?phpfunction createRange($number){
    $data = [];
    for($i=0;$i<$number;$i++){
        $data[] = time();
    }
    return $data;}$data =createRange(10);foreach($data as $value){
    sleep(1);//这里停顿1秒,我们后续有用
    echo $value.PHP_EOL;}
Copy after login

Learn how to use yield in php in one minute (share)

The time is the same. If yield is used:

<?phpfunction createRange($number){
    for($i=0;$i<$number;$i++){
        yield time();
    }}$data =createRange(10);foreach($data as $value){
    sleep(1);//这里停顿1秒,我们后续有用
    echo $value.PHP_EOL;}
Copy after login

Learn how to use yield in php in one minute (share)
, the time interval is one second, so through the example of yield, we know that it is not like the first example to store the contents of the for loop in memory. , but consumed one by one.

Example of reading a file

Create a txt file and write:

第1行
第2行
第3行
第4行
第5行
第6行
第7行
第8行
Copy after login
<?phpfunction readTxt(){
    # code...
    $handle = fopen("./test.txt", &#39;rb&#39;);

    while (feof($handle)===false) {
        # code...
        yield fgets($handle);
    }

    fclose($handle);}foreach (readTxt() as $key => $value) {
    # code...
    sleep(1);
    echo $value;}
Copy after login

Use php to read the file, it is read line by line
Learn how to use yield in php in one minute (share)

Recommended study: "PHP Video Tutorial"

The above is the detailed content of Learn how to use yield in php in one minute (share). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template