What is Anonymous Function in PHP

Anonymous is a normal PHP function but there is no specified name. Anonymous function seems like a normal/regular PHP function, it’s has a code block and run when it called, return value, it’s takes arguments as well. The major different between regular PHP function and Anonymous function are:

Anonymous function doesn’t need any name to declare the function but regular PHP function must need a name to declare.

Anonymous Function in PHP
Anonymous Function in PHP

From this image, you can see the  Anonymous function has no name between function keyword and.

And another major different is Anonymous function has a semicolon (;) after the function definition (see the image above). These are very major different between regular and Anonymous function.

 

In the a above image’s anonymous function is valid but not callable yet from anywhere. So it isn’t useful, To create a callable anonymous function we need to do a little more. I will show that rest of the article. So don’t worry

 

The Anonymous function is extremely useful as a value of a callback function. It can be really useful in certain situations as well. I will explain to you how to create an Anonymous function, how to use it and how to use it as a value of callback function.

To create an Anonymous function and access it, you can do a couple of handy things with it. For example,

  • Create an anonymous function and assign it to a variable, then call that anonymous function by using that assigned variable.
  • Create an anonymous function and pass it as an argument to another function. (callback function)

 

Creating Anonymous function and assign into variable:

Create an anonymous function and store that into a variable, Something like that

Here you can see, I have created a function and storing that into $anonymousVariable variable and calling. Now we can call access this anonymous function by using this $anonymousVariable variable. I am calling the anonymous function by this way echo $anonymousVariable('World'); here ‘World’ is the argument of the anonymous function.    

 

From this above code snippet, you will get this output.

PHP Anonymous function
PHP Anonymous function

 

 Create Anonymous function and pass it as an argument to another function:

One of the useful use of Anonymous is, build a callback function. A callback is a function (you will create) and passes to another function as an argument. Some PHP built is function allow add custom functions (e.g array_map() ). I will show this example with using array_map()  function. See the code snippet below.  

 

From this above code snippet, you will get this output.

Output of Anonymous function

So, now you explored about what is Anonymous function and some basic usage of it. Hope this article will help you to understand the about Anonymous function.