In Slim Framework, there is a protect
function that wraps callables within a function (i.e. another callable). The description in the manual says:
What if you want to literally store a closure as the raw value and not have it invoked? You can do that like this:
$app->myClosure = $app->container->protect(function () {});
Looking into the source code, I see this:
/**
* Protect closure from being directly invoked
* @param Closure $callable A closure to keep from being invoked and evaluated
* @return Closure
*/
public function protect(\Closure $callable)
{
return function () use ($callable) {
return $callable;
};
}
I'm wondering what the point of that is. Here I did my own test:
$foo = function() {
echo "Hello";
};
$bar = function () use ($foo) {
return $foo;
};
var_dump($foo);
var_dump($bar);
This is what I got:
object(Closure)#1 (0) {
}
object(Closure)#2 (1) {
["static"]=>
array(1) {
["foo"]=>
object(Closure)#1 (0) {
}
}
}
I can call $bar()
to return the callable but why would I do that if I can just use $foo
? Can someone please explain the purpose of this?