Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^74) CHAPTER 7 ■ REFLECTION API
■Note You can find a complete reflection API reference at http://www.php.net/language.oop5.
reflection. You may also wish to use the http://lxr.php.net/source/php-src/ext/
reflection/ source browser to see how the API works internally and view some of the more advanced
usage scenarios included with the extension.
Rather than just telling you about the class declarations, I’ll show you how to use reflection
to expose the class declarations with PHP itself. To see a complete and up-to-date export of the
entire reflection API, create the following script:
<?php
Reflection::export(new ReflectionExtension('reflection'));
?>
This will print out a very long listing, detailing every single class, method, and parameter
for the entire reflection API. This export was achieved through the use of the Reflection class’s
export() method.
Nearly all parts of the reflection API implement the interface reflector, and
ReflectionExtension is no exception. Reflection::export() prints a recursive output of the
reflector passed into it, and since all reflectors must implement export() themselves as part of
the interface, it is called all the way down the tree.
In this case, you start with with ReflectionExtension, which will, in turn, export all its
classes and interfaces and then all their methods and parameters.
You can even use reflection to create an export of every single built-in PHP class. To do
this, first you need to determine which classes are loaded. Fortunately, PHP provides the
get_declared_classes() function for just this purpose:
<?php
foreach(get_declared_classes() as $class) {
Reflection::export(new ReflectionClass($class));
}
?>
The get_declared_classes() function returns all classes, even the built-in classes, but
what if you want to get just your own user-declared classes?


Retrieving User-Declared Classes.


All you need to do to retrieve just the classes you declared is to reflect on each class to determine
if it is a user-defined class. Listing 7-1 demonstrates how to do this.

Listing 7-1. Reflecting Only User-Defined Classes

class userClass {
public function userMethod($userParameter='default') {}
}

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

Free download pdf