Simple introduction to the use of generator in PHP

Source: Internet
Author: User
Tags rewind


Summary: What is Generator starting with PHP 5.5, PHP has added a new feature, which is Generator, the Chinese translator builder. The generator can be simply used to implement an iterative iteration of the object, let's start with a small example of the official. Xrange in PHP, we all know that there is a function called ...

What is Generator

Starting with PHP 5.5, PHP has added a new feature, that is Generator , the Chinese translation 生成器 . The generator can be simply used to implement an iterative iteration of the object, let's start with a small example of the official.

Xrange

In PHP, we all know that there is a function called range , which is used to generate an array of arithmetic progression, and then we can iterate over this array foreach . That's exactly what you want.


foreach (Range (1, 2) as $num) {    echo "{$num}\n";}

This section of the code will output the first item is 1, the last item is 100, the tolerance is 2 arithmetic progression. This is the order in which it is executed. First, an array is generated, with range(1, 100, 2) a arithmetic progression like the one above, and the foreach array is iterated in.

So, there is a problem, if I want to generate 1 million numbers? Then we're going to have to use hundreds of megabytes of memory. Although the memory is very cheap now, but we can not so waste memory. Then our generators will be in handy. Consider the following code.


function xrange ($start, $limit, $step = 1) {    yield $start;    $start + +;} foreach (Xrange (1, 2) as $num) {    echo "{$num}\n";}

The result of this code is exactly the same as the previous code, but the internal principle is turned upside down.

As we said earlier, the preceding code range generates an array and then foreach iterates over the array to fetch a value. But this code, we have redefined a xrange function, in the function, we used a keyword yield . We all know the definition of a function, and hopefully it returns a worthwhile time to return return with. Well yield , that, too, can return a value, but it return 's completely different.

Using yield keywords, you can let the function break at run time, while saving the context of the entire function and returning an Generator object of type. When the method of the object is executed, the context at the time of the break is reloaded, and next continues until the next occurrence, and yield if it does not appear again yield , the entire generator is considered to be finished.

In this way, our function calls above can be written in the equivalent way.


$nums = xrange (1, 2), while ($nums->valid ()) {    echo $nums->current (). "\ n";    $nums->next ();}

Here, $num is an Generator object. Here we see three methods, valid current and next . When our function is finished and there is no yield interruption, then we are xrange done with the function, then the valid method becomes false . Instead, the current current yield value is returned, which is where the generator's function is interrupted. Then after the next method is called, the function continues until the next yield occurrence, or the function ends.

Okay, here we go yield . By "generating" a value and returning it. Actually, yield it can be written in this way $ret = yield; . As with the return value, this is where a value is passed into the function when it continues executing the function, which can be Generator::send($value) used. For example.


function sum () {    $ret = yield;    echo "{$ret}\n";} $sum = SUM (), $sum->send (' I am from outside. ');

This way, the program prints out send the string that the method passed in. Both yield sides can have a call at the same time.


function xrange ($start, $limit, $step = 1) {    $ret = yield $start;    $start + +;    echo "{$ret}\n";}

And like this, send() you can return the next yield return.

Other methods of Generator

Generator::key ()

For yield , we can use this, yield $id => $value which is, we can get through the key method $id , and current the method returns the $value .

Generator::rewind ()

This method can help us to have the generator restart execution and save the context, and return yield the first returned content. The method is implicitly invoked the first time it is executed send rewind .

Generator::throw ()

This method throws an exception to the generator.

Postscript

yieldAs a new feature of PHP 5.5, let's use a new approach to iterate data efficiently. At the same time, we can also use yield to implement the co-process.

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.