Category Archives: Anonymous function or Lambda function

Anonymous function or Lambda function

An anonymous function is simply a function with no name.

A Lambda is an anonymous function that can be assigned to a variable or passed to another function as an argument. If you are familiar with other programming languages like Javascript etc., you will be very familiar with anonymous functions.

// Regular function
function dosomething () {
return “Hello there”;
}

Function can be called something like:

echo dosomething();
// Returns “Hello there”

An anonymous function has no name so you would define it like this:

// Anonymous function
function () {
return “Hello there”;
}

How to use Ananymous functions –

Because the function has no name, you can’t call it like a regular function.

// assiging to variable, Anonymous/lamda function

$dosomething = function () {
return “Hello there”;
}

// Calling Ananymous function
echo $dosomething();
// Returns “Hello there”

To use the anonymous function, we need to assign it to a variable and then call that variable as a function.

You could also pass the function to another function, like this:

// Pass Ananymous\Lambda to another regular function
function anotherfunction ($dosomething){
echo $dosomething();
}

// Calling function
anotherfunction(function(){
return “Hello there”;
});