As I promised in the section that you just read, I’d like to finish this tutorial by showing you how to use reflection for verifying whether or not a specified class can be instantiated from client code. To achieve this, the reflection API provides the handy “isInstantiable()” method, which can be used in the following way: // 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 if the reflected class can be instantiated if ($reflector->isInstantiable()) { echo 'Reflected class is instantiable'; // displays 'Reflected class is instantiable' } else { echo 'Reflected class is not instantiable'; } Since the sample “User” class can indeed be instantiated, in the above checking block the “isInstantiable()” method will return a value of TRUE. Nonetheless, if you use it with an abstract class or with one that declares its constructor protected or private, the method will return FALSE. While checking if it’s possible to create instances of a class seems to be at first sight a rather pointless task, this is far from being true. This reflection process is often found in frameworks that implement some sort of dispatcher mechanism, and in some dependency injection containers as well. So, if you need to inspect classes an runtime with an acceptable level of automation, the methods offered by the reflection API are definitely an option worth looking at. Final thoughts In this sixth part of the series, I illustrated with some easy-to-grasp code samples how to use the power of reflection to know if a class has been defined abstract and final, and if it implements a specified interface. As you saw for yourself, performing all of these tasks was a straightforward process, meaning that you shouldn’t have major problems using the previous reflection methods within your own PHP applications. In the last episode, the focus will be on how to take advantage of reflection to verify whether a class is native or user-defined. Don’t miss the final article!
blog comments powered by Disqus |
|
|
|
|
|
|
|