What is Closure Object and how do I get the anonymous function return as parameter?

Asked

Viewed 460 times

13

Let’s say I have a class, and in that class i have a method, and in a parameter that method it is possible to use a anonymous function thus:


Class and method:

class Classe {
    private $exemplo = [];
    public function add($parametro1, $parametro2){
        $this->exemplo['parametro1'] = $parametro1;
        $this->exemplo['parametro2'] = $parametro2;
    }
}

Use:

$classe = new Classe;
$classe->add('parâmetro 1 aqui', function(){
    return 'retorno da função anonima para o parâmetro 2';
});

If I give a print_r() in the array $exemplo of my class, the result will be as follows:

Array ( [parametro1] => parâmetro 1 aqui [parametro1] => Closure Object ( ) )

What exactly is a Closure Object and how can I take what was returned in this anonymous function?

2 answers

5


Just call this variable as a function:

$classe->exemplo['parametro2']();

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I just switched to public to facilitate the example, if you want to keep the variable private, you can only call the function passed within the class itself.

The Closure Object is the type of data contained there, i.e., it is an object that contains a function that potentially encloses local variables from which it was defined.

  • Very good congratulations

4

In PHP, anonymous functions equals the instance of the class called Closure.

For example:

$a = function () {};

var_dump($a instanceof Closure); // bool(true)

To catch the return of a Closure you need to call her.

In the case of our example above, just call it so:

$a();

In case you assign a Closure a property, you cannot call it that way highlighted above. You must use a function:

call_user_func($this->closure, $parametro);

Or use the method of Closure called __invoke.

 $this->closure->__invoke($parametro);

Look in the Handbook and you’ll find that the Closure, because it is an object, it has some specific methods, which can change its behavior.

Browser other questions tagged

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