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

Asked

Viewed 103 times

2

I know that in the javascript the use of 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 to use the Self Invoking Function - functions that can be called at the same time that are declared.

Example:

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

    return 3;
})()


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

The exit is:

1
2
3

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

What other possible advantages are the use of Self Invoking Function in PHP7?

1 answer

3


The resource goes in the direction of what we call, in other languages, 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 can even call an anonymous function) is the possibility of defining the function dynamically. This example that you put up is not exactly good, so I will assemble another one. Suppose a function that performs sum of squares:

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

You can use it like this:

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

The exit must 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 run time:

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

We can use it like this:

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

Exit:

1
4
9
16
  • Look, that example was fine, huh.

  • I improved it. Now yes it is suitable.

  • For those who don’t like PHP, until you know a lot, huh.

  • 1

    I was a PHP programmer. I think I told you before.

  • 1

    I think there’s going to be a "Mortar" like this

Browser other questions tagged

You are not signed in. Login or sign up in order to post.