PATCH: anonymous functions in PHP

From: Date: Sun, 18 Mar 2007 23:41:16 +0000
Subject: PATCH: anonymous functions in PHP
Groups: php.internals 
Request: Send a blank email to internals+get-28399@lists.php.net to get a copy of this message
We've been daydreaming about the ability to do something like this in PHP: $data = array("zoo", "orange", "car", "lemon", "apple"); usort($data, function($a, $b) { return strcmp($a, $b); }); var_dump($data); # data is sorted alphabetically In the past, people have been told to use the travesty that is create_function() to emulate this kind of behavior, well, it turns out to be a minor patch to the parser to pull that into the core. You can find my prototype patch at http://pastebin.ca/400871 (against PHP_5_2) The way it works is by making the expression: function() {} evaluate to the (generated) name of the anonymous function. $foo = function() {}; sets $foo to a string like "__zend_anon_1", which can then be passed around as a callback name, just like the way that create_function() works, except that you don't need to use crazy quoting to declare any kind of moderately complex function. There's one minor flaw in my implementation for ZTS enabled systems (just need to move the anon function counter into CG() to solve that. So, the question is, do we want this in PHP? --Wez.

« previous php.internals (#28399) next »