PHP的create_function()与仅使用eval() [英] PHP's create_function() versus just using eval()

查看:132
本文介绍了PHP的create_function()与仅使用eval()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,您具有create_function()函数,该函数会创建一个独特的名为lambda的函数,如下所示:

$myFunction = create_function('$foo', 'return $foo;');
$myFunction('bar'); //Returns bar

实际上,这样做是否更好(除了更简单之外):

do{
 $myFunction = 'createdFunction_'.rand();
}
while(function_exists($myFunction));
eval("function $myFunction(\$foo) { return \$foo; }");
$myFunction('bar'); //Returns bar

create_function真的更好吗? (除了更容易的事实之外)

解决方案

根据我对相关文档的理解,[1]他们都做同样的事情,create_function()只是为您提供了一个唯一的函数名称./p>

要解决有关此问题的其他评论:

可以将

create_function分配给变量,使该函数可被代码的其他部分访问,而eval仅对给定范围有用.

eval()很有可能在当前作用域中运行,但是无论如何函数定义都会转储到全局名称空间中.[2]因此,无论何时定义一个函数,都可以在程序中的其他任何地方访问它.

使用eval()将使全局函数列表混乱,而create_function()则不会

create_function()仅返回带有新函数名称的字符串,[3]而不是某些特殊的回调类型.因此,这两种技术都会污染您的全局名称空间.

因此,除了create_function()更容易之外,它似乎没有eval()更好.

脚注:

[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

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:

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

这篇关于PHP的create_function()与仅使用eval()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆