Get source code of user-defined class and functions?

后端 未结 1 1747
生来不讨喜
生来不讨喜 2020-12-19 11:45

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.

相关标签:
1条回答
  • 2020-12-19 12:18

    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...

    0 讨论(0)
提交回复
热议问题