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:

//Create an anonymous function and assign it to a PHP variable.
$myAnonymousFunction = function(){
    echo "Hello World!";
};

//Call our anonymous function.
$myAnonymousFunction();

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:

//This anonymous function takes in a parameter
//called $name.
$sayHello = function($name){
    echo "Hello $name!";
};

//Call our anonymous function and pass in
//the parameter.
$sayHello('Wayne');

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:

//Create our first anonymous function.
$functionOne = function(){
    echo 'Hi everybody';
};

//Create our second anonymous function.
$functionTwo = function($function){
    $function();
};

//Pass one anonymous function into another.
$functionTwo($functionOne);

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.