

In this article, we look at the ability of PHP code to inspect itself, using the Reflection API introduced with PHP 5. We will build a tool that lets us automatically convert any class to a fully functional REST service, without writing a single line of dedicated binding code.
PHP has been designed as a high-level dynamic scripting language for the web. Dynamic languages, unlike static languages, retain rich information about the source code's meaning and structure for the entire duration of its execution. Such information covers function and class identifiers, parameters, types, interfaces, relationships etc.
We can easily see this with PHP, since we are able refer to variables and functions just by having their string names at our disposal, or even evaluate entire code fragments from a string at runtime (such features, of course, should be used in moderation):
Reflection is the ability of your program's code to tap into this rich information, in order to understand its own definitions and structure. This is used for a wide array of tasks, such as automating unit tests, building automatic documentation from source code, creating auto-generated reports and more.
The idea for reflection support in PHP has seen its beginning as early as PHP 4, by introducing a set of functions that describe the script runtime environment. Some examples include:
Those methods, while still useful, suffer from a number of limitations. For example, get_class_methods() cannot differentiate between static and instance methods, nor is there a way to learn more about a method's parameters, or in which file the class was defined.
This is why the introduction of the new Reflection API, starting with PHP5, is a major and very welcome addition to the language.
The Reflection API is a set of classes with an easy and consistent interface, allowing us to retrieve information about the declared functions, classes, down to details such as the PHPDoc comment that applies to a function, method or a class.
In this article, we'll use the Reflection API to build a reusable tool that will automatically expose the public methods of any class we choose, as a REST web service.
A REST service can be quickly described by the following rules:
error (holding the error message, if the service encountered a problem) or result (if it was executed properly).To test our work, we'll use the following class, which returns some information about the employees in a company:
Our goals are:
Employees.service.php?method=getDetails&fullName=Jessica+Conner.Let's call the class RestService. The constructor will accept an object, and pass it to method runAsService(), where we'll do the actual reflection work and invoke the method.
We will be doing all of our error handling via exceptions (Employees throws exceptions on bad input, as well), so the constructor should catch any exception and output the exception message as a JSON object, in an appropriate form for the service clients:

