HomePHP Page 3 - Getting Information on a Reflected Class with the Reflection API
The getDefaultProperties() and getDocComment() reflection methods - PHP
In this second part of a series, I explore some handy methods of the PHP Reflection API. They allow you to retrieve miscellaneous information about a class, including its name and containing file, as well as its starting and ending lines.
As you learned in the previous section, once a reflector object has been tied to a specific class, it’s very easy to collect information about its internal structure. So far, I've showed how to use reflection to get the name of a class, along with its constants, but it’s possible to find out much more about it.
To demonstrate this, below I wrote a simple script that shows how to get the default properties declared by the “User” class, along with the data included within its doc block. The script that does that looks like this:
// create instance of 'User' class
$user = new User();
// create instance of Reflection class and pass in 'User' class as argument
print_r($reflector->getDocComment()); // displays /** * A sample user class * * @param id fname lname email */
That was really easy to achieve, wasn’t it? By calling the new “getDefaultProperties()” and “getDocComment()” methods, it’s feasible to get the default properties declared by the “User” class along with the information embedded in its document block. As you can see, both methods return data in the form of arrays, which can be easily dumped to the browser or eventually stored in variables for further processing.
Now that you've learned how to use a couple of additional methods provided by the reflection API, it’s time to explore a few others. However, before I do that, I’d like to stress one important thing with reference to the previous example: while “getDefaultProperties()” does a decent job returning the set of default properties declared by a reflected class, in many situations it’s desirable to know their level of visibility as well.
Does this mean that the reflection API isn’t capable of doing such a thing? Fear not; it can do this by using a specialized class called “ReflectionProperty,” which will be properly analyzed in a future article. For the moment though, be patient and read the following section. In it I’m going to discuss how to use the API for collecting information about the physical location of the “User” class inside the file system.
Now, click on the link below and keep reading, please.