PHP learning -- generator Generators, -- generator generators_PHP tutorial

Source: Internet
Author: User
PHP learning: Generators and generators. PHP learning -- generator Generators, -- generator generators generator overview (PHP55.5.0, PHP7) generator provides an easier way to implement simple object iteration, comparison of PHP learning-Generators generators and Generators generators
Generator overview

(PHP 5> = 5.5.0, PHP 7)

The generator provides an easier way to implement simple object iteration. compared with defining classes that implement the Iterator interface, the performance overhead and complexity are greatly reduced.

The generator allows you to write code in the foreach code block to iterate a group of data without creating an array in the memory. This will limit your memory or occupy a considerable processing time. On the contrary, you can write a generator function, just like a normal custom function. different from a normal function, a generator can return multiple times as needed, to generate the value to be iterated.

A simple example is to use a generator to re-implement the range () function. The standard range () function generates an array in the memory that contains each value in its range, and then returns the array. The result is multiple large arrays. For example, calling range (0, 1000000) will cause memory usage to exceed 100 MB.

As an alternative, we can implementXrange ()Generator, you only need enough memory to create an Iterator object and track the current state of the generator internally. in this way, you only need less than 1 kB of memory.

Example #1 implement range () as a generator

 = 0) {throw new LogicException ('step must be-VE');} for ($ I = $ start; $ I >=$ limit; $ I ++ = $ Step) {yield $ I ;}}/ ** note that the output results of range () and xrange () are the same. */Echo 'single digit odd numbers from range (): '; foreach (range (1, 9, 2) as $ number) {echo "$ number ";} echo "\ n"; echo 'single digit odd numbers from xrange (): '; foreach (xrange (1, 9, 2) as $ number) {echo "$ number" ;}?>

The above routine will output:

Single digit odd numbers from range():  1 3 5 7 9 Single digit odd numbers from xrange(): 1 3 5 7 9 
Generator objects

When a generator function is called for the first time, an object of the internal Generator class is returned. this object implements the Iterator interface in much the same way as a forward-only iterator object wocould, and provides methods that can be called to manipulate the state of the generator, including sending values to and returning values from it.

Generator syntax

A generator function looks like a common function. The difference is that a common function returns a value, and a generator can generate many values required by yield.

When a generator is called, it returns an object that can be traversed. when you traverse this object (for example, through a foreach loop), PHP will call the generator function every time a value is required, and save the status of the generator after a value is generated, in this way, the call status can be restored when the next value needs to be generated.

Once more values are no longer needed, the generator function can exit, and the code that calls the generator can continue to be executed, just as an array has been traversed.

Note:

A generator cannot return values: doing so produces a compilation error. However, the return null is a valid syntax and it will terminate the generator to continue execution.

Yield keywords

The yield keyword is the core of the generator function. Its simplest call form looks like a return statement. The difference is that normal return will return the value and terminate the function execution, yield returns a value to call the code of this generator cyclically and only suspends the execution of the generator function.

Example #1 Example of a simple value generation

  

The above routine will output:

123

Note:

Internally, consecutive integer indexes are matched for the generated values, just like an unassociated array.

If you use yield in an expression context (for example, on the right of a value expression), you must use parentheses to enclose the yield declaration. For example, this is valid:

$data = (yield $value);

This is not legal, and a compilation error occurs in PHP5:

$data = yield $value;

The parenthetical restrictions do not apply in PHP 7.

This syntax can be used with the Generator: send () method of the Generator object.

Specify a key name to generate a value

PHP arrays support joined key-value pairs, and generators support the same. In addition to generating simple values, you can also specify the key name when generating values.

As shown below, generating a key-value pair is very similar to defining an associated array.

Example #2 generate a key-value pair

   $ Fields ;}} foreach (input_parser ($ input) as $ id =>$ fields) {echo "$ id: \ n "; echo "$ fields [0] \ n"; echo "$ fields [1] \ n" ;}?>

The above routine will output:

1:    PHP    Likes dollar signs2:    Python    Likes whitespace3:    Ruby    Likes blocks

Like the simple value type generated earlier, key-value pairs generated in an expression context also need to be surrounded by parentheses:

$data = (yield $key => $value);
Generate null value

Yield can be called to generateNULLValue and an automatic key name.

Generate Example #3NULLS

   

The above routine will output:

array(3) {  [0]=>  NULL  [1]=>  NULL  [2]=>  NULL}
Use reference to generate value

The generated function can be generated by reference like a value. This is the same as returning references from functions (a reference is returned from the function): add a reference symbol before the function name.

Example #4 use references to generate values

   0) {yield $ value;}/** we can modify the value of $ number in the loop, and the generator uses the reference value to generate, so gen_reference () the internal $ value also changes. */Foreach (gen_reference () as & $ number) {echo (-- $ number). '...';}?>

The above routine will output:

2... 1... 0... 
Generator delegation via yield from nation ¶

In PHP 7, generator delegation allows you to yield values from another generator, Traversable object, or array by using the yield from keyword. the outer generator will then yield all values from the inner generator, object, or array until that is no longer valid, after which execution will continue in the outer generator.

If a generator is used with yield from, the yield from expression will also return any value returned by the inner generator.

Example #5 Basic use of yield from

   

The above routine will output:

1 2 3 4 5 6 7 8 9 10 

Example #6 yield from and return values

   getReturn();?>

The above routine will output:

1 2 3 4 5 6 7 8 9 10
Comparing generators with Iterator objects

The primary advantage of generators is their simplicity. much less boilerplate code has to be written compared to implementing an Iterator class, and the code is generally much more readable. for example, the following function and class are equivalent:

   fileHandle = fopen($fileName, 'r')) {            throw new RuntimeException('Couldn\'t open file "' . $fileName . '"');        }    }     public function rewind() {        fseek($this->fileHandle, 0);        $this->line = fgets($this->fileHandle);        $this->i = 0;    }     public function valid() {        return false !== $this->line;    }     public function current() {        return $this->line;    }     public function key() {        return $this->i;    }     public function next() {        if (false !== $this->line) {            $this->line = fgets($this->fileHandle);            $this->i++;        }    }     public function __destruct() {        fclose($this->fileHandle);    }}?>

This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. this also means that the same generator can't be iterated over multiple times: the generator will need to either be rebuilt by calling the generator function again, or cloned via the clone keyword.

From: http://php.net/manual/zh/language.generators.php

Generator overview (PHP 5 = 5.5.0, PHP 7) generator provides an easier way to implement simple object iteration...

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.