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

淺唱寂寞╮ 提交于 2019-12-04 11:37:12

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

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

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.

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!