Home  >  Article  >  Backend Development  >  Learn how to use yield in php in one minute (share)

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

慕斯
慕斯forward
2021-06-23 14:08:407919browse

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

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;}

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;}

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行
<?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;}

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete

Related articles

See more