PHP: Assign a function to a variable.

This is a short guide on how to assign an anonymous function to a variable in PHP and then call it. Note that these kind of functions are sometimes referred to as lambda functions.

Let’s start off with a simple example with no parameters:

In the code above, we created a very basic anonymous PHP function and assigned it to a variable called $myAnonymousFunction. As a result, we were then able to call the function in question by referencing $myAnonymousFunction.

Anonymous function with parameters.

Now, let’s create an anonymous PHP function that takes in parameters:

As you can see, this example doesn’t differ too much from our first one. The only difference is that it takes in a parameter called $name and prints it out.

Passing one anonymous function into another.

You can also pass one anonymous function in as a parameter to another anonymous function:

In the code above, we created two functions and assigned them to PHP variables. The first function prints out a string, whereas the second one takes in a function as a parameter before calling it. Furthermore, we passed the first function into the second function.

As a result, the script above will print the words “Hi everybody” to the browser.

Crazy, right?

Oh, and by the way, I am not sorry for putting Dr. Nick’s voice in your head.

Facebook Comments