One of the most useful features of the reflection API is its ability to retrieve information about the methods defined by a selected class, to say nothing of its manipulation ability. And by manipulation, I mean the capability to invoke a reflected method with its incoming arguments. To elaborate on this concept, say that a script needs to check whether the "getFirstName()" method of the previous "User" class is public (which is true), and then call it from client code. Performing these tasks would be as easy coding the following snippet: // 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 a ReflectionMethod object $method = $reflector->getMethod('getFirstName');
// check to see if the reflected method is public, protected or private if ($method->isPublic()) { echo 'The method is public'; // displays 'The method is public' // invoke the reflected method echo $method->invoke($user); // displays 'Alejandro' } elseif ($method->isProtected()) { echo 'The method is protected'; } elseif ($method->isPrivate()) { echo 'The method is private'; } elseif ($method->isStatic()) { echo 'The method is static'; } Undoubtedly, a few interesting things are happening here. The above script uses a brand new reflection method called "getMethod()" to retrieve the "getFirstName()" method from the "User" class. This process returns an object of type ReflectionMethod, which can be used afterward for checking the visibility of "getFirstName()" and for calling it directly from client code. This one example should give you an excellent idea of the advantages in using reflection in PHP, and its possible applications in real-world environments. Having explained how to inspect and invoke a determined method within a reflected class, the last thing that I'm going to cover in this tutorial, will consist of showing how to use reflection to retrieve all of the public methods defined by that class. Now, to learn the full details of this process, click on the link below and read the section to come.
blog comments powered by Disqus |
|
|
|
|
|
|
|