Adi*_*are 11 php anonymous-function php-7.2
当我在字符串中有函数体时,如何动态创建匿名函数.
例如
$user = "John Doe";
$body = "echo 'Hello' . $user;";
$myFunct = function($user) {$body}; // How do I have function body here from string.
$myFunct($user);
Run Code Online (Sandbox Code Playgroud)
任何帮助将非常感激.
PS我正在寻找替代create_function()功能,这在PHP的早期版本中是有的.就像在create_function()中我们可以将函数体作为字符串传递一样,我想在字符串变量中定义匿名函数的主体.
ric*_*aan 16
如果您已经探索了所有其他选项并且绝对确定实现目标的唯一方法是使用字符串中的代码在运行时定义自定义函数,则可以使用两种方法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
Run Code Online (Sandbox Code Playgroud)
但是,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
Run Code Online (Sandbox Code Playgroud)
尽管如此,我强烈建议不要采用这些方法,并建议您找到其他方法来实现目标.如果你正在构建一个自定义代码混淆器,你可能最好创建一个php扩展,其中代码在执行前被去混淆,类似于ionCube Loader和Zend Guard Loader的工作方式.
| 归档时间: |
|
| 查看次数: |
683 次 |
| 最近记录: |