Lightweight "set" iterator-Generator, set-generator

Source: Internet
Author: User

Lightweight "set" iterator-Generator, set-generator

Generator is a new language feature added to PHP 5.5. However, it does not seem to be widely used by many PHP developers. Therefore, before learning about the improvements made by PHP 7 to Generator, let's take a simple but obvious example to understand what problems Generator solves for us.

 

Array of 10 million Integers

What if we want to "Create an array with the specified number of elements? We may write the following code without thinking about it:

function makeRange($range) {    $data = [];    for ($i = 0; $i < $range; $i++) {        $data[] = $i;    }    return $data;}

Then, in our development environment, we create an array of 10 thousand elements, 0.1 million elements, and 1 million elements. Everything looks like we thought.

makeRange(10000);makeRange(100000);makeRange(1000000);

However, when we create an array containing 10 million integers, the situation is different. The system does not allocate so much memory to us:

makeRange(10000000);

Ask PHP Generator for help

Defining PHP generator is simple and looks like defining a function:

function makeRangeByGenerator($range) {    for ($i = 0; $i < $range; $i++) {     yield $i;    }}

However, makeRangeByGenerator does not return values, nor creates the entire array in the memory. Instead, it only marks the value that should be generated for each loop through the keyword yield. Next, we can use generator like accessing a common set:

foreach ($makeRangeByGenerator(100) as $i) {    echo $i.'<br>';}

 

If you re-execute our PHP file, no error will be reported. In addition, we can see the value generated by generator on the page. This is a typical application scenario of generator. In short, Generator is a lightweight iterator that automatically remembers the status of each call and returns the correct value to us.
What improvements have PHP 7 made?

After learning about the basic usage of generator, we can see what improvements PHP 7 has made to generator.

  • PHP 7 allows us to add return values to generator, just as we define the return values of a function:

    Function makeRangeByGenerator ($ range ){

       for ($i = 0; $i < $range; $i++) {       yield $i;   }   return "Finish yielding";

    }

When all the elements of generator are iterated, we can use the getReturn () method to read the returned values of generator:

$gen = makeRangeByGenerator(100);foreach ($gen as $i) {    echo $i.'<br>';}echo $gen->getReturn();

*"The returned value of generator can be read only after all values of generator are iterated. Otherwise, an error is reported in PHP ."
-- Best practices*

  • The second improvement to generator in PHP 7 is to allow nesting. For example:

function outer() {    yield "PHP 7 ";    yield "is one of ";    yield "the best ";    yield from inner();}function inner() {    yield "programming languages in the world";}

We use the keyword from to introduce a new generator. When we traverse outer generator, we will find that it automatically generates the value of inner generator:

foreach(outer() as $str) {    echo $str;}
  • The second improvement to generator in PHP 7 is to allow nesting. For example:

function outer() {    yield "PHP 7 ";    yield "is one of ";    yield "the best ";    yield from inner();}function inner() {    yield "programming languages in the world";}

We use the keyword from to introduce a new generator. When we traverse outer generator, we will find that it automatically generates the value of inner generator:

foreach(outer() as $str) {    echo $str;}

This is all about PHP generator. In short, generator is a lightweight "set" iterator that remembers its own State. If you do not know about it before, it is time to consider where it can help you.

Learn more about high-quality IT technologies and broaden your horizons. Welcome to our partner Segmentfault.

 
 
 

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.