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.
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 ); |
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>
|
|
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.
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>
|
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>
|
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>
|
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 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 :
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>
|
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”.
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.