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)
On my understanding of the relevant docs,[1] they both do the same thing, create_function() just comes up with a unique function name for you.
To address some other comments on this question:
It may well be that eval() runs in the current scope, but function definitions get dumped into the global namespace anyway.[2] So whenever you define a function, it will be accessible everywhere else in your program.
create_function() only returns a string with the name of the new function,[3] not some special callback type. So, both techniques will pollute your global namespace.
So no, apart from create_function() being easier, it does not appear to be any better than eval().
Footnotes:
[1] https://www.php.net/manual/en/functions.user-defined.php ; http://au.php.net/create_function ; http://au.php.net/eval
[2] https://www.php.net/manual/en/functions.user-defined.php
[3] http://au.php.net/create_function