将一个php函数的的代码内容输出, export(print) php function code as string

技术分享 · Fecmall · 于 6年前 发布 · 1808 次阅读
$var = function ($message) {
                        return $message;
                    };

如果将变量的函数代码以字符串的方式输出呢?

可以用反射函数ReflectionFunction: Expanding on the suggestion to use the ReflectionFunction, you could use something like this:

$func = new ReflectionFunction('myfunction');
$filename = $func->getFileName();
$start_line = $func->getStartLine() - 1; // it's actually - 1, otherwise you wont get the function() block
$end_line = $func->getEndLine();
$length = $end_line - $start_line;

$source = file($filename);
$body = implode("", array_slice($source, $start_line, $length));
print_r($body);

参看: https://stackoverflow.com/questions/7026690/reconstruct-get-code-of-php-function

这个函数在Yii2中也有用到:

共收到 0 条回复
没有找到数据。
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics