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

Question:

Let's say I have a class , and in that class I have a method , and in a parameter of that method it's possible to 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;
    }
}

Use:

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

If I print_r() on the $exemplo array of my class , the result will look like this:

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

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

Answer:

Just call this variable as if it were a function:

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

See working on ideone . And on repl.it. Also posted on GitHub for future reference .

I just changed it 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 there, that is, it is an object that contains a function that potentially encloses local variables from where it was defined.

Scroll to Top