Anonymous Functions and Closures – the ‘use’ Keyword

Anonymous Functions
PHP 5.3 supports the use of anonymous functions. An unnamed function can be created and assigned to a variable and then the variable can be used like an actual function. Consider the following example:

1
2
3
4
5
6
7
8
<?php
$mult = function($x)
    {
    return $x * 5;
    };
 echo $mult(2);  // 10

?>

Closures
Closures are anonymous functions that have access to variables not defined within themselves. A closure can be created using the ‘use’ keyword. Consider the following example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

$multiply = function($multiplier)
{
    return function($x) use ($multiplier)  // 'use' gives access to multiplier
    {
        return $x * $multiplier;
    };
};
 
// $mul5 now contains a function that returns a number multiplied by 5
$mult5 = $multiply(5);
 
// $mul7 contains a function that returns a number multiplied by 7
$mult7 = $multiply(7);
 
echo $mult5(5);  // 25
echo $mult7(5);  // 35
 
?>

This is a little different to closures in JavaScript that automatically have access to variables outside their scope.

There are other ways to pass variables to the anonymous functions shown above. The variables could be passed as arguments or the variables could have been declared as global. The latter case can be become quite messy, however. Using the ‘use’ keyword is an elegant alternative to both methods.

Leave a Reply