PHP Manual: Reflection
Reflection
Introduction
PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.
The reflection API is an object-oriented extension to the Zend Engine, consisting of the following classes:
<?php |
Note: For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
ReflectionException
ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced.
ReflectionFunction
The ReflectionFunction class lets you reverse-engineer functions.
<?php |
Note: getNumberOfParameters() and getNumberOfRequiredParameters() were added in PHP 5.0.3, while invokeArgs() was added in PHP 5.1.0.
To introspect a function, you will first have to create an instance of the ReflectionFunction class. You can then call any of the above methods on this instance.
Example 19-34. Using the ReflectionFunction class
|
Note: The method invoke() accepts a variable number of arguments which are passed to the function just as in call_user_func().
ReflectionParameter
The ReflectionParameter class retrieves information about a function's or method's parameters.
<?php |
Note: getDefaultValue(), isDefaultValueAvailable() and isOptional() were added in PHP 5.0.3, while isArray() was added in PHP 5.1.0.
To introspect function parameters, you will first have to create an instance of the ReflectionFunction or ReflectionMethod classes and then use their getParameters() method to retrieve an array of parameters.
Example 19-35. Using the ReflectionParameter class
|
ReflectionClass
The ReflectionClass class lets you reverse-engineer classes.
<?php |
Note: hasConstant(), hasMethod(), hasProperty(), getStaticPropertyValue() and setStaticPropertyValue() were added in PHP 5.1.0, while newInstanceArgs() was added in PHP 5.1.3.
To introspect a class, you will first have to create an instance of the ReflectionClass class. You can then call any of the above methods on this instance.
Example 19-36. Using the ReflectionClass class
|
Note: The method newInstance() accepts a variable number of arguments which are passed to the function just as in call_user_func().
Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
ReflectionObject
The ReflectionObject class lets you reverse-engineer objects.
ReflectionMethod
The ReflectionMethod class lets you reverse-engineer class methods.
<?php |