PHP – Anonymous Functions and Closures (Part II)

Suppose the application should reduce the list of percentages to those that are equal to or greater than a user-specified value. For this we can use array_filter().

The array_filter() function accepts an input array and the name of a function, and produces a new array resulting from applying the callback function to each element of the input array. If the callback returns true then the element tested is included in the final output array. We have a slight problem, though– the documentation for array_filter() shows it only passes one value to the callback (the current array element to be examined). We need access to user-specified value as well. Closures will allow us to “reach out” outside the scope of the percentFilter_callback() function to see the value of $userPercent.

$userPercent = 0.5;
$userList = array_filter($percentVowels, function($percent) use ($userPercent)
return ($percent >= $userPercent);

Closures allow you controlled access to values to the parent scope of a function. The new syntax introduces the use keyword to specify which variables should be imported. The anonymous function is passed the current element of the $percentVowels array by array_filter(), but it has access to the value of $userPercent as well which is needed for the comparison.

Closures in PHP import the variable from the parent scope the same as if it were passed as an argument to the function and manipulating the variable does not have an effect outside the function (unless it was passed by reference).

However, it is important to keep in mind that closure is not the same thing as using global. global reference variables within the global scope of the script. Closures on the other hand can only bind to variables in the parent scope of a function, which make using them considerably safer than using global. I’ll leave you with this final example which highlights this difference between them:

$x = 42;
function foo() {
function fizz() {
global $x;
        echo $x;

function bar() {
$bizz = function () use ($x) { echo $x; };

Leave a Reply

Your email address will not be published. Required fields are marked *