PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

CHAPTER 5 ■ OBJECT TOOLS


Examining a Class


The Reflection ::export() method can provide a great deal of useful information for debugging, but we
can use the API in more specialized ways. Let’s work directly with the Reflection classes.
You’ve already seen how to instantiate a ReflectionClass object:


$prod_class = new ReflectionClass( 'CdProduct' );


Next, I will use the ReflectionClass object to investigate CdProduct within a script. What kind of
class is it? Can an instance be created? Here’s a function to answer these questions:


function classData( ReflectionClass $class ) {
$details = "";
$name = $class->getName();
if ( $class->isUserDefined() ) {
$details .= "$name is user defined\n";
}
if ( $class->isInternal() ) {
$details .= "$name is built-in\n";
}
if ( $class->isInterface() ) {
$details .= "$name is interface\n";
}
if ( $class->isAbstract() ) {
$details .= "$name is an abstract class\n";
}
if ( $class->isFinal() ) {
$details .= "$name is a final class\n";
}
if ( $class->isInstantiable() ) {
$details .= "$name can be instantiated\n";
} else {
$details .= "$name can not be instantiated\n";
}
return $details;
}


$prod_class = new ReflectionClass( 'CdProduct' );
print classData( $prod_class );


I create a ReflectionClass object, assigning it to a variable called $prod_class by passing the
CdProduct class name to ReflectionClass’s constructor. $prod_class is then passed to a function called
classData() that demonstrates some of the methods that can be used to query a class.



  • The methods should be self-explanatory, but here’s a brief description of each
    one: ReflectionClass::getName() returns the name of the class being examined.

  • The ReflectionClass::isUserDefined() method returns true if the class has been
    declared in PHP code, and ReflectionClass::isInternal() yields true if the class
    is built-in.

  • You can test whether a class is abstract with ReflectionClass::isAbstract() and
    whether it’s an interface with ReflectionClass::isInterface().

  • If you want to get an instance of the class, you can test the feasibility of that with
    ReflectionClass::isInstantiable().

Free download pdf