I've seen this practice in the php docs:
$foo = function() {
echo 'foo';
}
$foo();
Why would you do that instead of just:
function foo()
{
echo 'foo';
}
foo();
They're useful in a few ways. Personally I use them because they're easier to control than actual functions.
But also, anonymous functions can do this:
$someVar = "Hello, world!";
$show = function() use ($someVar) {
echo $someVar;
}
$show();
Anonymous functions can "import" variables from the outside scope. The best part is that it's safe to use in loops (unlike JavaScript) because it takes a copy of the variable to use with the function, unless you specifically tell it to pass by reference with use (&$someVar)
It's also often used to pass callbacks to functions such as array_map
and many others
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With