Anonymous Functions and Closures in PHP

PHP

If you are used to switch between JS and PHP programming, it obviously happened to you to miss some of JS flexibility in PHP. I felt it every time when declaring a callback function , being eager to apply something from JS like that:

var scope = 'internal';
setTimeout(_callback, 100);
// Callbacks
var _callback = function() {
	alert(scope);
}

And when I needed a recursive use, even like that:

(function(delay){
 timer = setTimeout(function(){
 	timer = setTimeout(arguments.callee, delay);
 }, delay);
})(100);

Whatsoever was it like, since PHP 5.3 that’s not an issue anymore. Of course it’s not a brand-new information, but being a lazy one, I usually study new available features only getting a new version of the language on the production platform. So, to be honest, I discovered availability of closures and anonymous functions in PHP recently. Here is a few examples from php.net :

echo preg_replace_callback('~-([a-z])~', function ($match) {
    return strtoupper($match[1]);
}, 'hello-world');
// outputs helloWorld
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');

It looks not less nice than JS variant. Just compare to how clumsy it was earlier:

$line = preg_replace_callback('|<p>\s*\w|',
	create_function('$matches','return strtolower($matches[0]);'), $line
);

What about closures ad scopes? Look at this:

$callback =
	function ($param1, $param2) use ($scopeParam1, %26$scopeParam2)
	{
		//
	};

array_walk($array, $callback);

Maybe it’s even better then in JS, you proxy all the scope variables you want via use operator.

As for recursion, it can be an implementation of Y-Combinator or a workaround, for instance, using references. Just check it out:

$factorial = function($n) use (%26$factorial) {
      if ($n <= 1)
        return 1;
      else
        return $n * $factorial($n - 1);
};

Thanks for references, Max