PHP Lambdas and Closures

Ashraful Alam
Oceanize Lab Geeks
Published in
1 min readDec 19, 2018

Lambdas and Closures are very useful solution in PHP and developers frequently get benefits from this. Many languages are support this feature like Javascript, Ruby, Python and so on. These functions are introduced in PHP 5.3.

What is Lambda Function?

It is an anonymous function that can be assigned by variable or passed by an argument with function. This is a simple function with no name but you could set variable for a function. You can also pass anonymous function to other functions or methods. Sometimes we need very simple function to server single job, In that time we can use Lambda otherwise we have to make global scope what not needed to to other purpose.

$sum = function ($a, $b) {
return $a + $b;
};

echo $sum(5, 5); // 10

One important note, We could not access any global variable directly inside the function. For instance,

$base = 100;
$sum = function ($a, $b) {
return $a + $b + $base;
};

echo $sum(5, 5); // Notice: Undefined variable: base

What is Closure Function?

Closure is similar with lambda or anonymous function with some extra benefits. We can access global variables by using use keyword and it allow us to access many global variable inside and anonymous function.

$base = 100;
$sum = function ($a, $b) use ($base) {
return $a + $b + $base;
};
echo $sum(5, 5); // 110

--

--