Self invoking functions in PHP 7. What are the advantages?

2

I know that in javascript it is very useful to use self invoking functions , especially when it comes to variable scope protection.

I was doing tests on PHP 7 and I see that we have the same possibility of using Self Invoking Function - functions that can be called at the same time that they are declared.

Example:

$gen = (function() {
    yield 1;
    yield 2;

    return 3;
})()


foreach ($gen as $number) {
    echo $number;
}

The output is:

1
2
3

In this case using the Generator , I see a lot of usefulness.

What are some other possible benefits of using Self Invoking Function in PHP7 ?

    
asked by anonymous 16.09.2015 / 17:41

1 answer

3

The resource goes in the direction of what we call, in other languages, from delegate functions . There's even a proposal for PHP 7 where the concept is even better developed .

The advantage of this type of function (which we may call an anonymous function) is the possibility of defining the function dynamically. This example you put is not exactly good, so I'm going to build another one. Suppose a function that performs a sum of squares:

$squares = (function($meu_array) {
    foreach ($meu_array as $elemento) 
    {
        yield $elemento * $elemento;
    }
})()

You can use this:

foreach ($squares(array(1, 2, 3, 4, 5)) as $number) {
    echo $number;
}

The output should be:

1
4
9
16
25

Now, suppose you want the sum of the squares up to a certain number, and that number is only known at runtime:

$squares = (function($meu_array, $limite) {
    foreach ($meu_array as $elemento) 
    {
        var $numero = $elemento * $elemento;
        if ($numero <= $limite ) yield $numero;
    }
})()

We can use this:

var $limite = 20;
foreach ($squares(array(1, 2, 3, 4, 5), $limite) as $number) {
    echo $number;
}

Output:

1
4
9
16
    
16.09.2015 / 17:52