如果您已经探索了所有其他选项,并且绝对确定实现目标的唯一方法是使用字符串中的代码在运行时定义自定义函数,那么您有两种选择create_function
.
快速的解决方案就是使用eval
:
function create_custom_function($arguments, $body) {
return eval("return function($arguments) { $body };");
}
$myFunct = create_custom_function('$user', 'echo "Hello " . $user;');
$myFunct('John Doe');
// Hello John Doe
然而,eval()
可以禁用。如果您甚至在服务器上也需要这种功能eval
不可用,您可以使用穷人的 eval:将函数写入临时文件,然后包含它:
function create_custom_function($arguments, $body) {
$tmp_file = tempnam(sys_get_temp_dir(), "ccf");
file_put_contents($tmp_file, "<?php return function($arguments) { $body };");
$function = include($tmp_file);
unlink($tmp_file);
return $function;
}
$myFunct = create_custom_function('$user', 'echo "Hello " . $user;');
$myFunct('John Doe');
// Hello John Doe
In all honesty though, I strongly recommend against these approaches and suggest you find some other way to accomplish your goal. If you're building a custom code obfuscator, you're probably better off creating a php extension where the code is de-obfuscated prior to execution, similar to how ionCube Loader and Zend Guard Loader work.