As I said in the preceding segment, getting all of the properties defined by the previous “User” class is really a breeze. The “User” class that you saw before defines only three private properties, but anyway it’s worthwhile to code an example, so you can see how easy is to accomplish this task. Having said that, here’s a script that retrieves in one go all of the properties declared by “User”: // 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 properties of reflected class print_r($reflector->getProperties()); // displays Array ( [0] => ReflectionProperty Object ( [name] => id [class] => User ) [1] => ReflectionProperty Object ( [name] => fname [class] => User ) [2] => ReflectionProperty Object ( [name] => lname [class] => User ) [3] => ReflectionProperty Object ( [name] => email [class] => User ) )
There you have it. Once a reflector object has been created, fetching all of the properties declared by the “User” class is reduced to calling the “getProperties()”reflection method and nothing else. What else can you ask for? Again, I’d like to clarify that the reflection API permits you to handle class properties in many other helpful and creative ways. However, in this series I only intended to introduce you to using the API’s most relevant methods in a few concrete cases. Learning the remaining ones will be left completely up to you. Final thoughts In this fourth part of the series, I demonstrated with a few basic examples how to use the PHP reflection API to retrieve useful information about the properties declared by a specific class. It’s fair to mention, though, that reflection allows you to do much more with properties of a class, aside from determining their visibility or knowing the values assigned to them. At the risk of being repetitive, the best place to get a full reference of reflection methods is the official PHP web site, so go ahead and take a look at it. It’s really worthwhile, trust me. Moving forward, in the upcoming tutorial I’m going to explore other useful reflection methods, which will allow you to get more detailed information about the properties of a class, such as if they’re static or even whether or not a specified property exists. Here’s my recommendation: don’t miss the next part!
blog comments powered by Disqus |
|
|
|
|
|
|
|