PHP's create_function() versus just using eval

2019-04-10 09:52发布

问题:

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)

回答1:

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:

create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.

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.

Using eval() will clutter the global function list, create_function() will not

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] http://au2.php.net/manual/en/functions.user-defined.php ; http://au.php.net/create_function ; http://au.php.net/eval

[2] http://au2.php.net/manual/en/functions.user-defined.php

[3] http://au.php.net/create_function



回答2:

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



回答3:

Personally, I've found that create_function() is extremely handy when sorting arrays.

In fact, I just searched the web, and it seems that the PHP documentation has a good example of this.

http://us.php.net/create_function

Scroll down to Example #3 Using anonymous functions as callback functions.



回答4:

create_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is only useful for the given scope.



回答5:

(apart from the fact that it is more easy)

I don't understand how you can dismiss this so readily. Given your two examples, which is easier to understand at a glance? Create_function tells you what you intend to accomplish. Eval doesn't.