如何将 create_function 重写为 PHP 中的箭头函数
How to rewrite create_function into an arrow function in PHP
我有一个 create_funtion
的简单代码,我想在匿名箭头函数中更改它。
$string = '3.2*2+1';
$compute = create_function("", "return (" . $string . ");" );
var_dump($compute());
如何从 create_funtion
中提取逻辑以使用箭头符号编写?
正如已经评论过的那样,请注意你传入 $string 的所有内容都会被评估,这对你的代码来说是一个潜在的威胁
你可以这样做:(闭包,与 php < 7.4 兼容)
$string = '3.2*2+1';
$compute = function() use ($string) { return eval("return $string;"); };
var_dump($compute());
箭头函数(php >= 7.4)
$string = '3.2*2+1';
$compute = fn() => eval("return $string;");
var_dump($compute());
使用箭头函数 $string
将在函数范围内可用:
$compute = fn() => eval("return $string;");
var_dump($compute());
或使用参数:
$compute = fn($s) => eval("return $s;");
var_dump($compute($string));
与create_function
一样:
Caution
This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics.
If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.
与eval
相同的注意事项:
Caution
The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
我有一个 create_funtion
的简单代码,我想在匿名箭头函数中更改它。
$string = '3.2*2+1';
$compute = create_function("", "return (" . $string . ");" );
var_dump($compute());
如何从 create_funtion
中提取逻辑以使用箭头符号编写?
正如已经评论过的那样,请注意你传入 $string 的所有内容都会被评估,这对你的代码来说是一个潜在的威胁
你可以这样做:(闭包,与 php < 7.4 兼容)
$string = '3.2*2+1';
$compute = function() use ($string) { return eval("return $string;"); };
var_dump($compute());
箭头函数(php >= 7.4)
$string = '3.2*2+1';
$compute = fn() => eval("return $string;");
var_dump($compute());
使用箭头函数 $string
将在函数范围内可用:
$compute = fn() => eval("return $string;");
var_dump($compute());
或使用参数:
$compute = fn($s) => eval("return $s;");
var_dump($compute($string));
与create_function
一样:
Caution This function internally performs an eval() and as such has the same security issues as eval(). Additionally it has bad performance and memory usage characteristics.
If you are using PHP 5.3.0 or newer a native anonymous function should be used instead.
与eval
相同的注意事项:
Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.