Php 将字符串转换为函数(可调用)并将其缓存
我正在尝试制作一个小的基准测试脚本,在这里我可以输入一些简短的代码来快速评估我的预期。我认为它类似于jsPerf,但出于安全原因,它受到密码保护 主循环应如下所示:Php 将字符串转换为函数(可调用)并将其缓存,php,eval,Php,Eval,我正在尝试制作一个小的基准测试脚本,在这里我可以输入一些简短的代码来快速评估我的预期。我认为它类似于jsPerf,但出于安全原因,它受到密码保护 主循环应如下所示: public function run(&$t, $count) { //Run setup function if(is_callable($this->setup)) call_user_func($this->setup); //Save inital time
public function run(&$t, $count) {
//Run setup function
if(is_callable($this->setup))
call_user_func($this->setup);
//Save inital time
$t($this->name);
//THE MAIN LOOP
for($i=0; $i<$count; $i++) {
call_user_func($this->fn);
}
//Save end time
$t($this->name."_end");
//return time difference
return $t[$this->name."-".$this->name."_end"];
}
如您所见,我使用call_user_func,而不是eval。除了它本质上的邪恶功能之外,出于性能原因,我想避免它。如果我正在测试一个代码,它的处理时间约为10ns,而评估时间约为100ns,那么我的结果将是相当随机的
这就是为什么我在寻找一种将字符串转换为可调用对象的方法。你可以把它当作一次性评估
$callable = string_to_callable("function() {echo \"Hello world!\";}");
$b->add(
//Name
"echo",
//callable object
$callable,
//Code seen in final reports
"echo \"...\""
);
可能吗
注:
我可以使用以下工具查看有趣的解决方法:
我真的希望我不需要上面的代码 除了创建新文件外,可能还有一个关闭技巧:
function string_to_callable($string) {
return eval("return function() {{$string}};");
}
//Code received from the user
$code = "echo \"Hello world!\";";
//Random name for a new function
$rndname = "fn_".rand(0,100000); //There are smarter ways to do this of course
//String of the new function
$func = "function $rndname() {{$code}}";
//Define a filename
$f = $rndname.".php";
//Put the code in the file
file_put_contents($f, "<?php\n$func\n?".">");
//Include the new script
include $f;
//Call the function
call_user_func($rndname);
//Delete the file
unlink($f);
function string_to_callable($string) {
return eval("return function() {{$string}};");
}