PHP Builder Details

Source: Internet
Author: User
The generator is PHP 5.5. Just introduced the function, perhaps people think that the generator role is not very obvious. However, generator functionality is really useful. This article is mainly to share with you the PHP generator detailed, hope to help everyone.

Advantages

Just say the concept of confused you listen to the end of the story, so we first say that the merits, may be able to arouse your interest. So what are the advantages of the generator, as follows:

    • The generator will have a very big impact on the performance of your PHP application

    • PHP code saves a lot of memory when it runs

    • More suitable for calculating large amounts of data

So, how do these magical features work? Let's give an example first.

Concept Introduction

First of all, drop the generator concept without saying, and look directly at a simple PHP function:

function Createrange ($number) {    $data = [];    for ($i =0; $i < $number; $i + +) {        $data [] = time ();    }    return $data;}

This is a very common PHP function that we often use when working with arrays. The code here is also very simple:

    1. We create a function.

    2. The function contains a for loop, and we loop the current time into the $data.

    3. The For loop executes and returns the $data.

It's not over, let's go. Let's write a function that loops out the return value of the function:

$result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);//pause here for 1 seconds, and we'll use    echo $value later. ' <br/> ';}

Let's look at the results of the operation in the browser:

 

There is no problem. (Of course sleep (1) effect can not see)

Think of a problem

We notice that when the function createrange is called, the value of the pass is 10, a small number. Assume that a value of 10000000 (10 million) is now passed.

So, inside the function createrange, the For loop needs to be executed 10 million times. and 10 million values are placed inside the $data, while the $data array is placed in memory. Therefore, it consumes a lot of memory when calling the function.

Here, the generator is ready to go.

Creating generators

We directly modify the code, we pay attention to the observation:

function Createrange ($number) {for    ($i =0; $i < $number; $i + +) {        yield time ();}    }

Looking at this and the very similar code, we removed the array $data and did not return any content, but instead used a keyword yield before time ().

Using the generator

Let's run the second piece of code again:

$result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);    echo $value. ' <br/> ';}

We miraculously discovered that the output value is not the same as the first time without using the generator. Here the value (timestamp) is spaced between 1 seconds.

The interval of one second is actually the result of sleep (1). But why is there no interval for the first time? That's because:

    • When the generator is not used: The For loop results within the Createrange function are quickly placed in $data and returned immediately. So, the Foreach loop is a fixed array.

    • When using the generator: The value of Createrange is not a one-time fast build, but relies on a foreach loop. The Foreach loop is once and for executes once.

Here, you should have a clue to the generator.

In-depth understanding of generators

Code anatomy

Let's dissect the code just now.

function Createrange ($number) {for    ($i =0; $i < $number; $i + +) {        yield time ();}    } $result = Createrange (10); This invokes the function we created above, foreach ($result as $value) {    sleep (1);    echo $value. ' <br/> ';}

Let's restore the code execution process.

    1. First call the Createrange function, pass in Parameter 10, but the for value executes once and then stops, and tells the value that the foreach first loop can use.

    2. foreach begins the loop on the $result, comes in first to sleep (1), and then starts using the for-given value to perform the output.

    3. foreach prepares the second loop and, before starting the second loop, it requests the For loop again.

    4. The For loop then executes again, telling the resulting timestamp to foreach.

    5. foreach Gets the second value, and the output. Because of the sleep (1) in foreach, the For loop is delayed by 1 seconds to generate the current time

So, throughout the execution of the code, there is always only one record value participating in the loop, and there is only one piece of information in memory.

The memory is always the value of a loop, regardless of how big the incoming number is, because all result sets are not immediately generated.

Conceptual understanding

Here, you should have probably understood what a generator is. Below we say the generator principle.

First, define a concept: The generator yield keyword is not a return value, his professional term is called the output value, just to generate a value

So what is the Foreach loop in the code? In fact, PHP will return an object of the generator class when it uses the generator. foreach iterates over the object, and every iteration, PHP calculates the next value that needs to be iterated through the generator instance. This way, foreach will know the value of the next iteration.

Also, it stops immediately after the for loop executes in the run. Wait for the next loop of foreach again and for the next value to be requested, the For loop executes again, and then immediately stops again. The end is not executed until the condition is not met.

Practical development of applications

Many PHP developers do not understand the generator, in fact, mainly do not understand the field of application. So, what are the applications of the generator in real-world development?

Read large files

PHP Development many times to read large files, such as CSV files, text files, or some log files. If these files are large, such as 5 G. At this point, it is not realistic to read all the contents into memory directly at once.

This generator can come in handy. A simple example: reading the text file

We create a text document and randomly enter a few lines of text in it to sample the read. The complete code is as follows:

<?phpheader ("Content-type:text/html;charset=utf-8"), function Readtxt () {    $handle = fopen ("test.txt", ' RB ');    while (feof ($handle) ===false) {        yield fgets ($handle);    }    Fclose ($handle);} foreach (Readtxt () as $key = = $value) {    echo $value. ' <br/> ';}

Through the output we can see that the code is completely normal.

However, the code execution rules behind it are a little bit different. Using the generator to read the file, first read the first line, the second read the second row, and so on, each time loaded into the memory of the text only one row, greatly reducing the use of memory.

This way, you can write code just like a small file, even if you don't have to worry about reading the text on G.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.