5

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.

3
  • 1
    You can open the file and parse using php to get it. Commented Oct 26, 2011 at 16:41
  • 1
    Check here- stackoverflow.com/questions/7026690/… Commented Oct 26, 2011 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. Commented Oct 26, 2011 at 19:29

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

$numLines = $endLine - $startLine + 1;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.