gpt4 book ai didi

php - 将php代码转换为字符串,与eval()相反

转载 作者:行者123 更新时间:2023-12-02 21:44:52 28 4
gpt4 key购买 nike

如何将可调用(匿名函数)转换为字符串进行评估?

我正在尝试在 phpunit 中编写使用 runkit 的单元测试覆盖方法。特别是,runkit_method_redefine() 需要一个字符串参数,稍后将调用 eval()

我想要对我的测试代码进行语法突出显示,所以我不想在字符串内编写代码,所以我想做类似的事情

deEval(function(){ 
return 1;
});

这将输出

"return 1;"

如何轻松完成此操作(例如,不执行源文件的 fopen、查找源代码行、解析等)?

最佳答案

注意:我不喜欢这个解决方案,也不会向任何人推荐它,但它确实解决了问题中提出的问题。


class CallableStringifier
{
private static $callables = array();

public static function stringify($callable)
{
$id = count(self::$callables);
self::$callables[$id] = $callable;
return 'return ' . __CLASS__ . "::call($id, func_get_args());";
}

public static function call($id, $args)
{
return call_user_func_array(self::$callables[$id], $args);
}
}

这适用于您的特定用例(本质上是create_function())。如果您只是eval(),它将无法工作,因为它依赖于函数上下文内部。

示例:

$func = create_function('$arg1', CallableStringifier::stringify(function($arg1) {
return $arg1;
}));

echo $func(1); // outputs 1

See it working

关于php - 将php代码转换为字符串,与eval()相反,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19704151/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com