-1

what is the benefit of using the anonymous function like this

//anonymous function

$hello = function(){
 echo "hello world";
};

$hello();

instead of using a regular function like this

//regular function

function hello()
{
  echo "hello world";
}

hello();
Mohammad Istanboli
  • 755
  • 1
  • 8
  • 19
  • i use them so rarely i usually forget what they are –  Dec 16 '16 at 00:59
  • That's similar to asking what's the benefit of using OOP, or using `switch()` over if / else. Technically, absolutely none. It's just a way of getting your code organized and intuitive and get work done faster. – Havenard Dec 16 '16 at 02:05

2 Answers2

2

In your first example, the benefits are negligible. The real benefit of anonymous functions is when you (as their name suggests), never give them a name, and pass them directly to another function.

The following is in pseudocode, since anonymous functions are a language agnostic concept. Say you have a function like:

function do-after-5-seconds(f) {
    sleep(5000);
    f();
}

You can then use it like:

do-after-5-seconds(function() {
    print("Hello!");
});

There would be very little point in giving the "hello printing function" a name, since it will never be used anywhere else. It's thus given directly to do-after-5-seconds.

This is a petty example, but often you'll have functions that you'll never use again, so there's no point in polluting the namespace by naming them.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
0

What is function? A unit of functionality that can be invoked and unit of code reuse. Sometimes you need only the first part: ability to invoke and do actions, but you don't want to reuse it at all and even make it visible to other parts of code. That's what anonymous functions essentially do.

Developer
  • 168
  • 1
  • 2
  • 13