Tag Archives: Lambda

Closure

A Closure is essentially the same as a Lambda apart from it can access variables outside the scope that it was created.

For example:
<?php
 $user = "PHPCodez";
 // Create a Closure 
 $greeting = function() use ($user) { 
 echo "Hello $user"; 
 };

$greeting();

As you can see above, the Closure is able to access the $user variable. because it was declared in the use clause of the Closure function definition.

If you were to alter the $user variable within the Closure, it would not effect the original variable. To update the original variable, we can append an ampersand. An ampersand before a variable means this is a reference and so the original variable is also updated.

Closures are also useful when using PHP functions that accept a callback function like array_map, array_filter, array_reduce or array_walk.

The array_walk function takes an array and runs it through the callback function.

Again, you can access variables outside the scope of the Closure by using the use clause:

In the example above, it probably wouldn’t make sense to create a function to just multiply two numbers together. If you were to create function to do a job like this, then come back to the code a while later you will probably be thinking why did you bother create a globally accessible function only to be used once? By using a Closure as the callback, we can use the function once and then forget about it.

Lambda

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 or Ruby, you will be very familiar with anonymous functions.

Because the function has no name, you can’t call it like a regular function. Instead you must either assign it to a variable or pass it to another function as an argument.

Lambdas are useful because they are throw away functions that you can use once. Often, you will need a function to do a job, but it doesn’t make sense to have it within the global scope or to even make it available as part of your code. Instead of having a function used once and then left lying around, you can use a Lambda instead.

Of course, you have been able to use the create_function function in PHP for a while now. This basically does the same job.