Frankly speaking, the process of getting and manipulating properties of a reflected class is very similar to the one used for working with reflected methods. To illustrate this concept, below I coded a simple example that shows how to retrieve all of the properties declared by the previous “User” class and determine their level of visibility. The example is as follows: // create instance of 'User' class $user = new User();
// create instance of Reflection class and pass in 'User' class as argument $reflector = new ReflectionClass('User');
// check the visibility of retrieved properties foreach ($reflector->getProperties() as $property) { if ($property->isPublic()) { echo 'Property : ' . $property->getName() . ' is public<br />'; } elseif ($property->isProtected()) { echo 'Property : ' . $property->getName() . ' is protected<br />'; } elseif ($property->isPrivate()) { echo 'Property : ' . $property->getName() . ' is private<br />'; } /*displays the following Property : fname is private Property : lname is private Property : email is private */ }
See how easy it is to obtain relevant information about the properties of a class via reflection? I bet you do! In the above example, the visibility assigned to the properties of the “User” class is determined by first creating a new ReflectionProperty object, and then by using its “isPublic(),” “isProtected()” and “isPrivate()” methods. Naturally, the reflection API makes it easier to manipulate class properties in all sorts of clever ways, but for the sake of brevity I’ll keep the examples shown in this and other tutorials rather simple, so you can more quickly grasp its underlying logic. Having demonstrated how to use reflection to learn the level of visibility assigned to each property of the “User” class, in the last section of this article I’m going to show you how to get all of the properties of that sample class in one single step. To learn the full details of this process, click on the link below and read the next few lines.
blog comments powered by Disqus |
|
|
|
|
|
|
|