Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get source code of user-defined class and functions?

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.

like image 647
mpen Avatar asked Oct 26 '11 16:10

mpen


1 Answers

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

like image 191
mpen Avatar answered Sep 27 '22 21:09

mpen