In PHP you have the create_function() function which creates a unique named lambda function like this:
$myFunction = create_function('$foo', 'return $foo;');
$myFunction('bar'); //Returns bar
Is this actually any better (apart from being more easy) then just doing:
do{
$myFunction = 'createdFunction_'.rand();
}
while(function_exists($myFunction));
eval("function $myFunction(\$foo) { return \$foo; }");
$myFunction('bar'); //Returns bar
Is create_function really better? (apart from the fact that it is more easy)
Using eval() will clutter the global function list, create_function() will not, apart from that there's no big difference. However, both methods require writing the function body inside a PHP string which is error-prone and if you were working on my project I would order you to just declare a helper function using the normal syntax.
Anonymous functions in PHP are so poorly implemented that your code is actually better off not using them. (Thankfully this will be fixed in PHP 5.3).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With