18

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();
4
  • 10
    see Anonymous functions Commented Mar 3, 2013 at 16:55
  • 1
    You would do this so that you'll be able to pass that function around from object to object... Commented Mar 3, 2013 at 16:57
  • Sometimes anonymous functions are very usefull. For example you have a form and you need to validate some field. You are certain, that you will not need this function anywhere, but here and you need to pass callable argument. IMO anonymous functions are way to go in such situation. Commented Mar 3, 2013 at 16:58
  • There are convenience advantages beyond storing them in variables. Mostly they're used for not cluttering the global namespace with one-off callbacks. Commented Mar 3, 2013 at 16:58

3 Answers 3

18

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)

Sign up to request clarification or add additional context in comments.

2 Comments

An example of it being used in a loop might be useful.
fyi - if you're skimming for the best answer, i would say the highly upvoted comment above by @Laxus is also very helpful (if not more so)
4

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

Comments

0

It is extremely useful in some particular cases. For example

Server::create('/')
    ->addGetRoute('test', function(){
        return 'Yay!';
})

The above code snippet is an example of simple routing in a REST based application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.