PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

Because ReflectionMethod provides us with getFileName(), getStartLine(), and
getEndLine() methods, it’s a simple matter to extract the method’s source code.


Examining Method Arguments


Now that method signatures can constrain the types of object arguments, the ability to examine the
arguments declared in a method signature becomes immensely useful. The Reflection API provides the
ReflectionParameter class just for this purpose. To get a ReflectionParameter object, you need the help
of a ReflectionMethod object. The ReflectionMethod::getParameters() method returns an array of
ReflectionParameter objects.
ReflectionParameter can tell you the name of an argument, whether the variable is passed by
reference (that is, with a preceding ampersand in the method declaration), and it can also tell you the
class required by argument hinting and whether the method will accept a null value for the argument.
Here are some of ReflectionParameter’s methods in action:


$prod_class = new ReflectionClass( 'CdProduct' );
$method = $prod_class->getMethod( "__construct" );
$params = $method->getParameters();


foreach ( $params as $param ) {
print argData( $param )."\n";
}


function argData( ReflectionParameter $arg ) {
$details = "";
$declaringclass = $arg->getDeclaringClass();
$name = $arg->getName();
$class = $arg->getClass();
$position = $arg->getPosition();
$details .= "\$$name has position $position\n";
if (! empty( $class ) ) {
$classname = $class->getName();
$details .= "\$$name must be a $classname object\n";
}


if ( $arg->isPassedByReference() ) {
$details .= "\$$name is passed by reference\n";
}


if ( $arg->isDefaultValueAvailable() ) {
$def = $arg->getDefaultValue();
$details .= "\$$name has default: $def\n";
}


return $details;
}


Using the ReflectionClass::getMethod() method, the code acquires a ReflectionMethod object. It
then uses ReflectionMethod::getParameters() to get an array of ReflectionParameter objects. The
argData() function uses the ReflectionParameter object it was passed to acquire information about the
argument.
First, it gets the argument’s variable name with ReflectionParameter::getName(). The
ReflectionParameter::getClass() method returns a ReflectionClass object if a hint’s been provided.

Free download pdf