获取用户定义的类和函数的源代码?

发布于 2024-12-11 22:40:12 字数 153 浏览 3 评论 0原文

有没有一种方法可以获取类或方法的源代码?我正在查看 ReflectionClass,但我没有看到一。

Is there a method for getting the source code of a class or method? I'm looking at the ReflectionClass, but I don't see one.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

隔纱相望 2024-12-18 22:40:12

我能想到的最好的办法是:

$class = new ReflectionClass($c);
$fileName = $class->getFileName();
$startLine = $class->getStartLine()-1; // getStartLine() seems to start after the {, we want to include the signature
$endLine = $class->getEndLine();
$numLines = $endLine - $startLine;

if(!empty($fileName)) {
    $fileContents = file_get_contents($fileName);
    $classSource = trim(implode('',array_slice(file($fileName),$startLine,$numLines))); // not perfect; if the class starts or ends on the same line as something else, this will be incorrect
    $hash = crc32($classSource);
}

编辑:这对于像这样定义的类来说效果不佳:

class Foo { }

说这是 2 行长,而它应该只有 1 行...

Best I could come up with:

$class = new ReflectionClass($c);
$fileName = $class->getFileName();
$startLine = $class->getStartLine()-1; // getStartLine() seems to start after the {, we want to include the signature
$endLine = $class->getEndLine();
$numLines = $endLine - $startLine;

if(!empty($fileName)) {
    $fileContents = file_get_contents($fileName);
    $classSource = trim(implode('',array_slice(file($fileName),$startLine,$numLines))); // not perfect; if the class starts or ends on the same line as something else, this will be incorrect
    $hash = crc32($classSource);
}

Edit: This doesn't work well with classes defined like this:

class Foo { }

Says this is 2 lines long when it should only be 1...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文