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

12

Let's say I have a class , and in that class I have a method , and a you can use an anonymous function like this:

Class and method:

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

Usage:

$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 Closure Object and how can I get what was returned in this anonymous function ?

    
asked by anonymous 21.11.2015 / 00:57

2 answers

5

Just call this variable as if it were a function:

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

See running on ideone .

I just moved to public to make the example easier, if you want to keep the variable private, you can only call the function passed inside the class itself.

The Closure Object is the data type contained therein, ie it is an object that contains a function that potentially encloses local variables from where it was defined.

    
21.11.2015 / 01:25
2

In PHP, anonymous functions are equivalent to the instance of the class called Closure .

For example:

$a = function () {};

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

To get the return of a Closure you need to call it.

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

$a();

In case you assign a Closure to a property, you can not call it in that way highlighted above. You should use a function:

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

Or use the method of Closure called __invoke .

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

See in the Manual and you will find that Closure , because it is an object, has some specific methods that can change its behavior.

    
23.11.2015 / 15:06