<?php
$args = '$user, $number';
$body = 'echo "#$number: Hello $user.\n";';
function _create_function_without_eval($args, $body) {
$func_name = sprintf('temp_func_%s', md5($body));
$code = sprintf("<?php if (!function_exists('%s')) {function %s(%s){%s}}", $func_name, $func_name, $args, $body);
$func_file = tempnam('/tmp', $func_name);
$handle = fopen($func_file, "w+");
fwrite($handle, $code);
fclose($handle);
include $func_file;
unlink($func_file);
return function(...$user_args) use ($func_name) {
return call_user_func_array($func_name, $user_args);
};
}
function _create_function_with_eval($args, $body) {
$func_name = sprintf('temp_func_%s', md5($body));
$code = sprintf("if (!function_exists('%s')) {function %s(%s){%s}}", $func_name, $func_name, $args, $body);
eval($code);
return function(...$user_args) use ($func_name) {
return call_user_func_array($func_name, $user_args);
};
}
$fn_deprecated = create_function($args, $body);
$fn_with_eval = _create_function_with_eval($args, $body);
$fn_without_eval = _create_function_without_eval($args, $body);
echo $fn_deprecated('Old Bob', '1');
echo $fn_without_eval('Bob without eval', 2);
echo $fn_with_eval('Bob with eval', 3);
preferences:
25.56 ms | 410 KiB | 5 Q