PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


}


if ( $method->isAbstract() ) {
$details .= "$name is abstract\n";
}
if ( $method->isPublic() ) {
$details .= "$name is public\n";
}
if ( $method->isProtected() ) {
$details .= "$name is protected\n";
}
if ( $method->isPrivate() ) {
$details .= "$name is private\n";
}
if ( $method->isStatic() ) {
$details .= "$name is static\n";
}
if ( $method->isFinal() ) {
$details .= "$name is final\n";
}
if ( $method->isConstructor() ) {
$details .= "$name is the constructor\n";
}
if ( $method->returnsReference() ) {
$details .= "$name returns a reference (as opposed to a value)\n";
}
return $details;
}


The code uses ReflectionClass::getMethods() to get an array of ReflectionMethod objects and then
loops through the array, passing each object to methodData().
The names of the methods used in methodData() reflect their intent: the code checks whether the
method is user-defined, built-in, abstract, public, protected, static, or final. You can also check whether
the method is the constructor for its class and whether or not it returns a reference.
There’s one caveat: ReflectionMethod::returnsReference() doesn’t return true if the tested method
simply returns an object, even though objects are passed and assigned by reference in PHP 5. Instead,
ReflectionMethod::returnsReference() returns true only if the method in question has been explicitly
declared to return a reference (by placing an ampersand character in front of the method name).
As you might expect, you can access a method’s source code using a technique similar to the one
used previously with ReflectionClass:


class ReflectionUtil {
static function getMethodSource( ReflectionMethod $method ) {
$path = $method->getFileName();
$lines = @file( $path );
$from = $method->getStartLine();
$to = $method->getEndLine();
$len = $to-$from+1;
return implode( array_slice( $lines, $from-1, $len ));
}
}


$class = new ReflectionClass( 'CdProduct' );
$method = $class->getMethod( 'getSummaryLine' );
print ReflectionUtil::getMethodSource( $method );

Free download pdf