HomePHP Page 3 - Introducing the Reflection API in PHP 5
Finding the name of a reflected class - PHP
In this first part of a series, we'll begin exploring some of the methods included with the Reflection API bundled with PHP 5. The interface allows developers to collect relevant information about a reflected class, including its name, its declared constants and properties, in a extremely straightforward way.
Any decent reflection library should be able to retrieve the most basic information about a target class, and the reflection API provided by PHP is no exception. However, you may be wondering how to use it with the previous interface and its implementing class. Below I've coded an example that shows the simplest way to use the API.
Pay close attention to the following code fragment, please:
// 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 name of reflected class
echo $reflector->getName(); // displays 'User'
As you can see above, I first created an instance of the sample “User” class only for demonstrative purposes, and second (here’s where the magic really happens), a new reflector object has been spawned from the native “ReflectionClass” class. This one is truly the workhorse of the entire reflection API; it takes as an as input argument the name of the class that needs to be reflected.
In this example, the string “User” has been passed to the constructor of the “ReflectionClass” class (don’t worry if your tongue gets stuck at this point). This process returns a reflector object that will allow you to retrieve valuable information about the “User” class that you saw in the previous section.
Since I’m just starting to explore the reflection API, the first thing that the above example does is invoke a method called “getName(),” which returns the name of the reflected class. But, wait a minute! We already knew that, right?
This time, yes, but there will be situations in which the name of the reflected class will not be known ahead of time, so using the “getName()” method is not so pointless as it may seem. Besides, the use of this method opens the door to working with many others, which will be covered in this tutorial and the ones to come.
At this stage, you've learned how to utilize one method of the reflection API to retrieve the name of the class being reflected. That was a fairly straightforward process, so it’s time to explore other methods that will allow us to get additional information about that class. The ones that will be discussed in the following section will return the name of the constant defined within the “User” class, so to learn how to use them, click on the link below and read the new few lines.