CHAPTER 5 ■ OBJECT TOOLS
You can even examine a user-defined class’s source code. The ReflectionClass object provides
access to its class’s file name and to the start and finish lines of the class in the file.
Here’s a quick-and-dirty method that uses ReflectionClass to access the source of a class:
class ReflectionUtil {
static function getClassSource( ReflectionClass $class ) {
$path = $class->getFileName();
$lines = @file( $path );
$from = $class->getStartLine();
$to = $class->getEndLine();
$len = $to-$from+1;
return implode( array_slice( $lines, $from-1, $len ));
}
}
print ReflectionUtil::getClassSource(
new ReflectionClass( 'CdProduct' ) );
ReflectionUtil is a simple class with a single static method, ReflectionUtil::
getClassSource(). That method takes a ReflectionClass object as its only argument and returns the
referenced class’s source code. ReflectionClass::getFileName() provides the path to the class’s file as
an absolute path, so the code should be able to go right ahead and open it. file() obtains an array of all
the lines in the file. ReflectionClass::getStartLine() provides the class’s start line;
ReflectionClass::getEndLine() finds the final line. From there, it’s simply a matter of using
array_slice() to extract the lines of interest.
To keep things brief, this code omits error handling. In a real-world application, you’d want to check
arguments and result codes.
Examining Methods
Just as ReflectionClass is used to examine a class, a ReflectionMethod object examines a method.
You can acquire a ReflectionMethod in two ways: you can get an array of ReflectionMethod objects
from ReflectionClass::getMethods(), or if you need to work with a specific method,
ReflectionClass::getMethod() accepts a method name and returns the relevant ReflectionMethod
object.
Here, we use ReflectionClass::getMethods() to put the ReflectionMethod class through its paces:
$prod_class = new ReflectionClass( 'CdProduct' );
$methods = $prod_class->getMethods();
foreach ( $methods as $method ) {
print methodData( $method );
print "\n----\n";
}
function methodData( ReflectionMethod $method ) {
$details = "";
$name = $method->getName();
if ( $method->isUserDefined() ) {
$details .= "$name is user defined\n";
}
if ( $method->isInternal() ) {
$details .= "$name is built-in\n";