Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why store function as variable in PHP

Tags:

php

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();
like image 998
Alexander Cogneau Avatar asked Mar 03 '13 16:03

Alexander Cogneau


2 Answers

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)

like image 129
Niet the Dark Absol Avatar answered Oct 14 '22 07:10

Niet the Dark Absol


It's also often used to pass callbacks to functions such as array_map and many others

like image 26
juco Avatar answered Oct 14 '22 09:10

juco