Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's create_function() versus just using eval()

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)

like image 354
Pim Jager Avatar asked Dec 05 '22 07:12

Pim Jager


1 Answers

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

like image 167
too much php Avatar answered Dec 23 '22 17:12

too much php