Better anonymous functions in PHP5
I’m sure everyone knows that create_function is evil, while at the same time, so very appealing. The most significant problem are the memory leaks that occur every time `create_function()` is called (as it’s not really an anonymous function, just a randomly named function in the global scope). The below class sidesteps the problem by caching `create_function()` results, minimizing the actual number of functions that are created.
<?php
/**
* A create_function() wrapper to stop memory leaks when calling
* create_function multiple times with the same arguments
*
* @author Matthew Davey
*/
class AnonFunction
{
/**
* 'Hash' to hold our functions. The key is the function arguments
* concatenated with the function body.
*
* @var $functions array
* @private
* @static
*/
private static $functions = array();
/**
* Create a new function, or return a previous function
*
* @param string $arg function arguments
* @param string $body function body
* @return string name of function
*/
public static function Create($arg, $body)
{
if(!isset(self::$functions[$arg . $body]))
{
self::$functions[$arg . $body] = create_function($arg, $body);
}
return self::$functions[$arg . $body];
}
}
?>
Example
// New style
$f1 = AnonFunction::Create('', 'return "Hello World";');
$f2 = AnonFunction::Create('', 'return "Hello World";');
// Pass
assert('$f1 === $f2');
// Old style
$g1 = create_function('', 'return "Hello World";');
$g2 = create_function('', 'return "Hello World";');
// Fail
assert('$g1 === $g2');