问题描述
我知道这个问题似乎很怪异,但是有什么方法可以在运行时用PHP删除函数吗?
I know this question seems hacky and weird, but is there a way to remove a function at runtime in PHP?
我有一个在"if"块中声明的递归函数,并且希望该函数仅在该"if"块中才是有效"的.我不希望在此块之外调用此函数.
I have a recursive function declared in a "if" block and want that function to be "valid" only in that "if" block. I don't want this function to be callled outside this block.
我发现了 runkit_function_remove ,但.还有另一种方法吗?
I found out runkit_function_remove but runkit isn't enabled on my Web host. Is there another way to do that?
顺便说一句,我只支持PHP 5.1.0.
BTW I only support PHP 5.1.0.
我知道我的问题很棘手,但这正是我想做的事情:
I knew my question was hacky but here is the exact thing I want to do:
if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc())
{
function stripslashes_deep($value)
{
return is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
//runkit_function_remove('stripslashes_deep');
}
由于"Stripslashes_deep"仅在魔术引号"处于启用状态时才有效,因此我想在使用完它后摆脱它.我不希望人们依赖并非总是有的功能.我希望现在更加清楚.也欢迎非hacky解决方案建议!
Since "stripslashes_deep" will only live when Magic Quotes are ON, I wanted to get rid of it when I'm done with it. I don't want people to rely on a function that isn't always there. I hope it's clearer now. Non-hacky solution suggestions are welcome too!
推荐答案
来自 PHP函数手册:
该异常是通过runkit进行的.但是,您可以将函数定义为匿名函数和 unset
运行后,例如
The exception is through runkit. However, you could define your function as an anonymous function and unset
it after you ran it, e.g.
if (function_exists('get_magic_quotes_gpc') && @get_magic_quotes_gpc())
$fn = create_function('&$v, $k', '$v = stripslashes($v);');
array_walk_recursive(array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST), $fn);
unset($fn);
}
一些评论者正确地指出了(但如今在PHP中已不再是问题),您不能在其内部调用匿名函数.通过使用array_walk_recursive
,您可以绕开此限制.就个人而言,我只会创建一个常规函数,而不必为删除它而烦恼.它不会伤害任何人.只需给它起一个适当的名称即可,例如stripslashes_gpc_callback
.
Some commentors correctly pointed out (but not an issue any longer in PHP nowadays), you cannot call an anonymous function inside itself. By using array_walk_recursive
you can get around this limitation. Personally, I would just create a regular function and not bother about deleting it. It won't hurt anyone. Just give it a proper name, like stripslashes_gpc_callback
.
注意:评论后进行了编辑和压缩
这篇关于在运行时使用PHP删除函数(不带runkit扩展名)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!