Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^102) CHAPTER 7 ■ REFLECTION API


/**

* Divide two numbers
*
* @param int $a The value
* @param int $b The divisor
*/
public function divide($a, $b) { return $a+$b; }

}

$reflector = new DocumentingReflectionClass('demo');
foreach($reflector->getMethods() as $method) {
foreach($method->getAttributes() as $attribute) {
if($attribute InstanceOf WebServiceMethodAttribute) {
//If the code gets here, this method is safe to expose

//Get the class name
$class = $attribute->getMethod()->getDeclaringClass()->getName();

//Get the method name
$method = $attribute->getMethod()->getName();

//Get any data passed to the right of the attribute name
$data = $attribute->getData();

//Add the method to your web service (not included)
//$service->add(array($class, $method));
}
}
}

The result of this code is that only the add($a,$b) method is exposed because it has the
WebServiceMethod attribute. You can take this concept and expand on it, using the getData()
method to pass parameters.

Just the Facts


In this chapter, you learned about the reflection API structure and created a reference for your-
self by reflecting on the Reflection extension.
The reflection API’s get_declared_classes() and isUserDefined() methods can be combined
to automatically find classes you declared.
Using reflection-based capability determination, you can create applications that auto-
matically load available plug-ins. This approach uses the methods implementsInterface(),
hasMethod(), newInstance(), and invoke() (to invoke methods both statically and nonstatically).

McArthur_819-9C07.fm Page 102 Friday, February 22, 2008 8:59 AM

Free download pdf