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.
Asked
Active
Viewed 4,376 times
5
-
1You can open the file and parse using php to get it. – gustavotkg Oct 26 '11 at 16:41
-
1Check here- http://stackoverflow.com/questions/7026690/reconstruct-get-code-of-php-function – Vikk Oct 26 '11 at 16:43
-
I was hoping I could avoid reading in the file...but oh well. I just have to hope that the class/function doesn't start on the same line as some other code. – mpen Oct 26 '11 at 19:29
1 Answers
8
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...

mpen
- 272,448
- 266
- 850
- 1,236