Anonymous Functions and Closures in 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() {

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

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

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 :

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);


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, &$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 (&$factorial) {
      if ($n <= 1)
        return 1;
        return $n * $factorial($n - 1);

Thanks for references, Max