
Overview Of Generators:
Generator does not returns a value but generates a sequence of values. It is a normal function that instead of returning a value yields as many values as needed to get a desired result.
A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit, or require a considerable amount of processing time to generate.
A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.
The heart of a generator function is the yield keyword. In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function.
A Simple Generator:
<?php
function gen_one_to_ten(){
for($i=1;$i<=10;$i++){
yield$i;
}
}
$gen=gen_one_to_ten();
foreach($gen as $value){
echo"$value\t";
}
?>
Fibonacci Generator Example:
<?php
function fib($n)
{
$cur=1;
$prev=0;
for ($i=0; $i<$n; $i++) {
yield$cur;
$temp=$cur;
$cur=$prev+$cur;
$prev=$temp;
}
}
$fibs = fib(9);
foreach ($fibs as $fib) {
echo" ".$fib;
}
// prints: 1 1 2 3 5 8 13 21 34
?>
Object-oriented programming (OOP)
The precedence of an operator specifies how “tightly” it binds two expressions together. In general, operators have a set precedence, or order, in which they are evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator. For example, in the expression 8 + 5 * 2, the answer is 18 and not 26 because the multiplication (“*”) operator has a higher precedence than the addition (“+”) operator. Parentheses may be used to force precedence, if necessary. For instance: (8+2) * 4 evaluates to 40.
PHP provides a large number of predefined constants to any script which it runs. Magic constants have a funny syntax, placing two underscores before and after the constant’s word representation. There are nine magical constants that change depending on where they are used. For example, the value of _