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.

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.

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

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.

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

Alternatively using the instanceof can confirm that an object is actual 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:

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.

Related Posts