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


Convert php code to string, opposite to eval()

如何将可调用(匿名函数)转换为 eval 的字符串?

我正在尝试在 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

看到它工作

编写了一个不太高效的函数。(不考虑参数)

/**
 * Converts method code to string by reading source code file
 * Function brackets {} syntax needs to start and end separately from function body
 *
 * @param Callable $callable method to deevaluate
 *
 * @return string
 */
public function callableToString($callable) {
    $refFunc = new ReflectionFunction($callable);
    $startLine = $refFunc->getStartLine();
    $endLine   = $refFunc->getEndLine();
    $f      = fopen($refFunc->getFileName(), 'r');
    $lineNo = 0;
    $methodBody = '';
    while($line = fgets($f)) {
        $lineNo++;
        if($lineNo > $startLine) {
            $methodBody .= $line;
        }
        if($lineNo == $endLine - 1) {
            break;
        }
    }
    fclose($f);
    return $methodBody;
}