Generators of PHP 5.5

D

Generators of PHP 5.5

Generators of PHP 5.5-techfameplus.com
Generators of PHP 5.5-techfameplus.com

 

The generators are already available in other development languages ??such as Python, are one of the most interesting among those introduced with version 5.5 of PHP, they represent a solution to implement expressions aimed iteration of objects ( iterators ), without generating overhead, ie the use of ancillary resources, or the necessity of having to resort to classes that implement the interface default PHP for the iteration ( Iterator interface ).

Making use of the generators will be able to type in source codes articulated less than those required for the implementations of iterators and, at the same time, develop applications more performing at runtime; this is due to the fact that, through them, the use of the cycle foreach against a dataset does not require the filing of an array, in this way you will not have these memory allocations to exceed the maximum allowable limit and the time required for the execution will be faster.

Through the generators may be defined functions can operate as any other construct of the same type but specifically, instead of performing a single return, they will have many repetitions with how many will be those required to deplete the total iterations provided.

In this short article we will present the syntax required for the use of generators and presented some practical examples of their use.

Generators of PHP 5.5-techfameplus.com
Generators of PHP 5.5-techfameplus.com

Syntax of generators: the yield keyword

As for the mechanics on the operation of generators, it is necessary to emphasize that these were not designed for the restitution of return values, indeed, such an eventuality would lead to notification of a mistake on the part of the PHP parser, are instead allowed return no values ??for the termination of the generators themselves.

When you call a function based on the generators of php 5.5, it has the task of making available an object for iteration, the loop will result in a function call that will be repeated many times as you will be prompted for a value, and the last state of the generator will be recorded. This saving will then reactivate the generator at the time of the request of the next value.

The procedure will not be repeated endlessly of course, but take into account the number of iterations provided, once exhausted the task of the generator execution will continue with the rest of the instructions contained in the source.

At the base of the syntax of generators of php 5.5 there is a keyword, yield , essentially an expression based on it might remind education based on return (as in the common user-defined functions), but yield is not the task of stopping the ‘ execution of a function to return its value return, indeed, it must provide a value to the iteration cycle and pause the execution of the function without terminating the associated generator.

An elementary example of use of the keywords in the yield generators could be the following:

<? Php <font> </ font>/ * <font> </ Font>

definition and use of a function <font> </ font>

based on a generator <font> </ font>

* / <font> </ font>

/ / Function generator <font> </ font>

function semplice_ciclo () {<font> </ font>

/ / Range of values ??<font> </ font>

for ( $ x = 5; $ x <= 10; $ x + +) {<font> </ font>

/ / Conservation of values ??for the interaction <font> </ font>

yield $ x ; <font> </ font>

<font>} </ Font>

<font>} </ Font>

/ / Store the generator in a variable <font> </ font>

$ Count = semplice_ciclo (); <font> </ font>

/ / Loop the dataset provided by the generator <font> </ font>

foreach ( $ iterations as $ iteration ) {<font> </ font>

echo $ iteration . “\ n” ; <font> </ font>

<font>} </ Font>

?>

The function proposed plan to print on the screen all the digits in the range between “5” and “10” produced by a for loop with one unit increase, all the values ??that satisfy the condition set will then be “entrusted” to yield so that become available at a time when there will be a call to the function, the generator will cycle through values ??made available from education to the keywords associated to the last iteration planned. All this without allocating any launcher in memory, but with a mechanism similar to that of non-associative array, because the generator will automatically define the sequence of keys (in the form of whole numbers) relative to the values ??in cycling.

Note that the syntax of generators provides that, in case you want to allocate the outcome of a yield statement in a variable, it will be necessary to its definition in parentheses, so you can not use a format like this :

$ Variable yield = $ value ;

while the correct form will be:

$ Variable = (yield $ value );

 

Define key / value pairs using the generators

As anticipated, the generators support the automatic assignment of values ??to iterate over the keys, but you can also use a mechanism borrowed from that expected for associative arrays in this regard it is possible to analyze the simple example below:

<font> <font> <? Php </ font> </ font> <font> </ font> <font> <font>/ * </ Font> </ font> <font> </ font> <font> <font>

    definition of key / value pairs in the generators </ font> </ font> <font> </ font>

<font> <font>

* / </ Font> </ font> <font> </ font> <font> <font>

/ / String for the subdivision </ font> </ font> <font> </ font> <font> <font>

$ String = <<< 'EOF' </ font> </ font> <font> </ font> <font> <font>

a, Goofy, talking dog </ font> </ font> <font> </ font> <font> <font>

b, Pluto, talking dog </ font> </ font> <font> </ font> <font> <font>

c, Donald Duck, bird speaker </ font> </ font> <font> </ font> <font> <font>

EOF; </ font> </ font> <font> </ font> <font> <font>

/ / Function Generator </ font> </ font> <font> </ font> <font> <font>

get_key function ($ string) {</ font> </ font> <font> </ font> <font> <font>

        / / Split the string into rows </ font> </ font> <font> </ font> <font> <font>

    foreach ( explode ( "\ n" , $ string) as $ row) {</ font> </ font> <font> </ font>

<font> <font>

    / / Row splitting into substrings </ font> </ font> <font> </ font> <font> <font>

        $ Records = explode ( ',' , $ row); </ font> </ font> <font> </ font> <font>

<font>

    / / Extraction of the first element of each row </ font> </ font> <font> </ font>

<font> <font>

        $ Key = array_shift ($ records); </ font> </ font> <font> </ font> <font>

<font>

    / / Use of elements extracted as identifiers </ font> </ font> <font> </ font>

<font> <font>

        yield $ key => $ records; </ font> </ font> <font> </ font> <font> <font>

    } </ Font> </ font> <font> </ font> <font> <font>

} </ Font> </ font> <font> </ font> <font> <font>

/ / Loop the dataset </ font> </ font> <font> </ font> <font> <font>

foreach (get_key ($ string) as $ key => $ records) {</ font> </ font> <font> </ font>

<font> <font>

    echo $ key. </ Font> <font> "-" . $ Records [0]. </ Font> <font> "" . $ Records [1].

 </ Font> <font> "<br/> \ n" ; </ font> </ font> <font> </ font> <font> <font>

} </ Font> </ font> <font> </ font> <font> <font>

?> </ Font> </ font>

 

The code presented primarily contains a string, introduced through syntax Nowdoc , which is divided into three rows, each row in turn contains three substrings separated by commas, the application will only isolate the first element / value of each substring so to use it as a key, the other two elements of each substring will be associated with sequential numerical keys assigned automatically.

Even in this case is to consider that must be used parentheses to store a variable in the assignment of key / value pairs:

<font> <font> $ Var = (yield $ key => $ value); </ font> </ font>

When the assignment is not seen as syntactically correct format without brackets.

NULL values ??and calls for reference

The yield keyword can also be introduced without any arguments to be passed to it, in this case the values ??will be managed NULL and then, in fact, not of values, in this regard it is possible to present a simple example like the following:

<font> <font> <? Php </ font> </ font> <font> </ font> <font> <font>/ * </ Font> </ font> <font> </ font> <font> <font>

    generator without passing arguments to yield </ font> </ font> <font> </ font> <font> <font>

* / </ Font> </ font> <font> </ font> <font> <font>

valori_null function () {</ font> </ font> <font> </ font> <font> <font>

    foreach (range (5, 10) as $ x) {</ font> </ font> <font> </ font> <font> <font>

        yield; </ font> </ font> <font> </ font> <font> <font>

    } </ Font> </ font> <font> </ font> <font> <font>

} </ Font> </ font> <font> </ font> <font> <font>

var_dump (iterator_to_array (valori_null ())); </ font> </ font> <font> </ font> <font> <font>

?> </ Font> </ font>

Note that in this case the yield will collect information on the number of iterations given but at the same time, it will provide no value, or rather, it will only provide NULL, the functioniterator_to_array () allow you to copy the contents to dell’iterator ‘interior of an array, for which it will be possible to obtain an output in which the elements of the first will be proposed as indexed values ??of a vector:

<font> <font> array (6) {</ font> </ font> <font> </ font> <font> <font>    [0] => NULL [1] => NULL [2] => NULL [3] => NULL [4] => NULL [5] => NULL </ font>

</ font> <font> </ font > <font> <font>

} </ Font> </ font>

Another special case concerns the transfer of values ??for reference, it will be treated by placing the symbol “and commercial” or ampersand (“&”) before the name of the function, the same symbol, also known as reference operator , then precede the second argument the foreach loop, that is, the variable introduced by “as” that will be used for the assignment of values ??over the cycle, and this mechanism is basically the same as for the return of reference to functions, it can be verified through an example on the model of following:

<font> <font> <? Php </ font> </ font> <font> </ font> <font> <font>/ * </ Font> </ font> <font> </ font> <font> <font>

passing values ??</ font> </ font> <font> </ font> <font> <font>

by reference into generators </ font> </ font> <font> </ font> <font> <font>

* / </ Font> </ font> <font> </ font> <font> <font>

function & countdown () {</ font> </ font> <font> </ font> <font> <font>

    $ Start = 5; </ font> </ font> <font> </ font> <font> <font>

    while ($ start> 0) {</ font> </ font> <font> </ font> <font> <font>

        yield $ start; </ font> </ font> <font> </ font> <font> <font>

    } </ Font> </ font> <font> </ font> <font> <font>

} </ Font> </ font> <font> </ font> <font> <font>

foreach (countdown () as & $ result) {</ font> </ font> <font> </ font> <font> <font>

    echo (- $ outcome). </ Font> <font> "<br/> \ n" ; </ font> </ font> <font> </ font> <font> <font>

} </ Font> </ font> <font> </ font> <font> <font>

?> </ Font> </ font>

In the specific case of the proposed script, the variable $ result will be decreased uniformly at each iteration of the loop, the number of iterations of the foreach will be established previously by assigning it to the variable $ start of a value passed as a reference and assigned to education yield.

The objects of the class generator

The moment a function associated with a generator is invoked for the first time occurs the return of an object of class Generator; the task of this object is to implement the interface Iterator that at the semantic level shares some methods with Generator.

Specifically Generator provides the following capabilities with visibility level public :

  • rewind () : “rewinds” the iterator, exception will be thrown if the iteration has already begun;
  • valid () : returns “false” when the iterator has been closed, otherwise it returns “false”;
  • current () : returns the value provided by yield at the current moment;
  • key () : Returns the key associated with the value provided by yield at the current moment;
  • next () : Allows you to resume execution of the generator;
  • send () : provides values ??to the generator resulting in the recovery of its execution.

send () is not a common method with Iterator and has been introduced specifically for sending values ??to the function generator, is analyzed in this regard the following example:

<? Php <font> </ font>/ * <font> </ Font>

using the send () method <font> </ font>

to send values ??to the function of the generator <font> </ font>

* / <font> </ font>

function send () {<font> </ font>

    while (true) {<font> </ font>

        $ Text = yield; <font> </ font>

        echo $ text ; <font> </ font>

    <font>} </ Font>

<font>} </ Font>

$ Obj = send (); <font> </ font>

$ Obj -> send ( 'HTML.it' ); <font> </ font>

?>

As can be seen, the value sent to the function of the generator will be provided from education yield and in this way can be used exactly as any other variable by the function itself.

Also of note is the fact that the object of the Generator class can not be instantiated using the keyword “new”.

Conclusions

The generators are one of the new PHP 5.5, they allow you to iterate over data records that are allocated for this purpose in the memory array, also represent a viable alternative to the implementation of iterators, in this brief discussion has been described the correct syntax for their use and were shown some practical examples regarding their use by the instructions based on the yield keyword.

 


Leave a comment
Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Coffee for us