PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 5 ■ OBJECT TOOLS

As you have seen, the call() method is invoked when an undefined method is called by client
code. In this example, I maintain an object in a property called $thirdpartyShop. If I find a method in the
stored object that matches the $method argument, I invoke it. I blithely assume that the target method
does not require any arguments, which is where my problems begin. When I write the
call() method,
I have no way of telling how large the $args array may be from invocation to invocation. If I pass $args
directly to the delegate method, I will pass a single array argument, and not the separate arguments it
may be expecting. call_user_func_array() solves the problem perfectly:


function __call( $method, $args ) {
if ( method_exists( $this->thirdpartyShop, $method ) ) {
return call_user_func_array(
array( $this->thirdpartyShop,
$method ), $args );
}
}


The Reflection API


PHP’s Reflection API is to PHP what the java.lang.reflect package is to Java. It consists of built-in
classes for analyzing properties, methods, and classes. It’s similar in some respects to existing object
functions, such as get_class_vars(), but is more flexible and provides much greater detail. It’s also
designed to work with PHP’s object-oriented features, such as access control, interfaces, and abstract
classes, in a way that the older, more limited class functions are not.


Getting Started


The Reflection API can be used to examine more than just classes. For example, the ReflectionFunction
class provides information about a given function, and ReflectionExtension yields insight about an
extension compiled into the language. Table 5–1 lists some of the classes in the API.
Between them, the classes in the Reflection API provide unprecedented runtime access to
information about the objects, functions, and extensions in your scripts.
Because of its power and reach, you should usually use the Reflection API in preference to the class
and object functions. You will soon find it indispensable as a tool for testing classes. You might want to
generate class diagrams or documentation, for example, or you might want to save object information to
a database, examining an object’s accessor (getter and setter) methods to extract field names. Building a
framework that invokes methods in module classes according to a naming scheme is another use of
Reflection.


Table 5–1. Some of the Classes in the Reflection API


Class Description

Reflection Provides a static export() method for summarizing class information

ReflectionClass Class information and tools

ReflectionMethod Class method information and tools
Free download pdf