Anonymous functions (closures) can be created as local functions (thus not pollluting the global space, as Dathan suggested).
With the "use" keyword, variables that are passed to or created by the enclosing function can be used inside the closure. This is very useful in callback functions that are limited in their parameter list. The "use" variables can be defined outside the closure, eliminating the need to redefine them each time the closure is called.
function change_array($arr, $pdo)
{
$keys = array('a', 'c');
$anon_func = function(& $val, $key) use ($keys, $pdo)
{
if (in_array($key, $keys) {
$pdo->query('some query using $key');
$val = $pdo->fetch();
}
}
arr_walk($arr, $anon_func);
return $arr;
}
$pdo = new($dsn, $uname, $pword);
$sample = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4);
$sample = change_array($sample, $pdo);
(Of course, this example can be simpler without a closure, but it's just for demo.)