All About Closures in PHP

Closures have been around since PHP 5.3 and are sometimes referred to as anonymous functions. It is a standard part of modern programming paradigm and can be implemented in several other programming languages.

A Closure has no name of its own, it is often assigned to a variable or passed to another function a callback. It simply exists to execute and as such is a very useful tool refactor old code and adding clarity to your program.

// Declare a simple anonymous function
$welcome = function() {
    echo 'Hello Waldo ';
};

Understanding Closures by Example

Closures ordinarily have no access to the scope outside of where its defined and as a result, the example below will throw a PHP Notice because $name is not defined within the anonymous function below.

$name= 'Keith ';
$welcomeMessage = function() {
    return 'Welcome '.$name;
};
echo $welcomeMessage();

In the use case where access is required, Closures have their ability to access variable the parent scope via the key for use.

$name= 'Keith ';
$welcomeMessage = function() use ($name){
    return 'Welcome '.$name;
};

echo $welcomeMessage();

A copy of $name is now available to be manipulated within the function scope.
Closures can also be type-hinted and passed in as variables in the functions.

class MyClass
{
    public function getWelcomeMessage(Closure $callback, $firstname, $lastname)
    {
        return $callback($firstname, $lastname);
    }
}

$nameformat = function($firstname, $lastname) {
    return 'Hi '.ucfirst(strtolower($firstname)).' '.ucfirst(strtolower($lastname)).',';
};

$class = new MyClass();
echo $class -> getWelcomeMessage($nameformat, Keith, Sweat); // Hi Keith Sweat,

The ReflectionFunction class comes in handy when trying to detect Closures. Its job is to return information about a function.

$welcome = function(){
    returnHello world;
};

$reflection = new ReflectionFunction(welcome);
echo $reflection->isClosure(); // true

Alternatively using the instanceof can confirm that an object is actual Closure.

(function(){}) instanceof Closure; //

Closures as Callbacks

In the wild, Closures are used as callbacks. As Callbacks, they are passed as an argument to another function and can be used to modify the nature of that other function. Several built-in PHP functions like array_walk accept callbacks. For example:

$prices= [56.09, 22.45, 89.01, 67.50];

$prefixPrices= array_map(function($value) {
    return '£'.$value; 
}, 
$prices); //[£56.09, £22.45, £89.01, £67.5];

Closures allow us to write cleaner and cleaner code :). Hopefully, the examples above have helped to show how. To make your new-found understanding of Closures stick, find some way to implement it in your coding exercise this week.

0
0

Related Posts