If all of the methods covered previously weren’t good enough, the reflection API also provides an additional one called “getStaticProperties()” that allows you to collect all of the static properties defined by a class. The result is returned to client code as an associative array, which can be easily traversed via a “foreach” construct. Unfortunately, the “User” class that I’m using here for testing purposes doesn’t declare any static properties. Despite this issue, the following code sample should give you a clear idea of how to use this method in a concrete case: // 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 static properties of reflected class print_r($reflector->getStaticProperties()); // displays nothing That was pretty easy to accomplish, wasn’t it? As it was done previously with instance-level methods and properties, the “getStaticProperties()” method returns an array containing all of the static properties of a class. In the above code sample, for the reason mentioned before, the method simply will return an empty array. However, the example is more than enough to demonstrate the real functionality of this reflection method. And with this last example, we’ve come to the end of this article. As always, feel free to edit all of the code samples included in this tutorial, which surely will improve your skill in using the PHP reflection API. Final thoughts That’s all for the moment. In this firth episode of the series you learned a couple of additional methods included with the PHP reflection API. The first one allowed you to check the existence of a specified class property, and the second one permitted you to retrieve all of the static properties defined by that class. Of course, in the case of “User,” the latter task is rather pointless, as it declares no static properties, but in other situations it might be pretty useful. In the next tutorial I’m going to explain how to use the power of reflection to determine if a class is an implementer of a given interface, and if it’s been defined abstract and final as well. Don’t miss the upcoming article!
blog comments powered by Disqus |
|
|
|
|
|
|
|