In the preceding segment, I demonstrated how to use the “getName()” method provided by the native “ReflectionClass” class to obtain the name of the class being reflected. Since this operation was really easy to grasp, I’m now going to show you how to utilize a couple of additional methods to get the names and values of the constants declared by the reflected class. To do so, in the following lines I coded a brand new script that retrieves the HEADING constant, defined by the previous “User” class: // create instance of 'User' class $user = new User();
// create instance of Reflection class and pass in 'User' class as argument $reflector = new ReflectionClass('User');
// get constant in reflected class echo $reflector->getConstant('HEADING'); // displays 'Using the Reflection API in PHP 5'
// get an array of constants in reflected class print_r($reflector->getConstants()); // displays Array ( [HEADING] => Using the Reflection API in PHP 5 ) As seen above, retrieving the values assigned to the constants defined by a given class is only a matter of calling the “getConstant()” and “getConstants()” methods of the reflection API, and nothing else. The first of these methods takes the name of the constant that needs to be parsed, while the second one simply returns an array of constants, populated with their corresponding values. This basic code sample does reveal the impressive potential of the reflection API for inspecting the internal structure of a class. But this is only a humble beginning. The API comes packaged with many other handy methods that will be discussed in depth in subsequent tutorials of this series. Final thoughts In this introductory part of the series, I started exploring some of the methods included with the Reflection API bundled with PHP 5. As you saw for yourself, the interface allows you to collect relevant information about a reflected class, including its name, its declared constants and properties, in a extremely straightforward way. However, I’m only scratching the surface when it comes to the full capabilities that this API freely offers. Therefore, in the next part I’m going to show you how to use it for retrieving additional information about a target class, such as its starting and ending lines, the name of the file that contains the class, the interfaces that it implements and much more. Don’t miss the upcoming article!
blog comments powered by Disqus |
|
|
|
|
|
|
|