Reflection Table of Contents Introduction The Reflector interface The ReflectionException class The ReflectionFunction class The ReflectionParameter class The ReflectionClass class The ReflectionObject class The ReflectionMethod class The ReflectionProperty class The ReflectionExtension class Extending the reflection classes 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: ]]> For details on these classes, have a look at the next chapters. If we were to execute the code in the example below: Basic usage of the reflection API ]]> &example.outputs; class Exception ] { - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [6] { Property [ protected $message ] Property [ private $string ] Property [ protected $code ] Property [ protected $file ] Property [ protected $line ] Property [ private $trace ] } - Methods [9] { Method [ final private method __clone ] { } Method [ public method __construct ] { - Parameters [2] { Parameter #0 [ $message ] Parameter #1 [ $code ] } } Method [ final public method getMessage ] { } Method [ final public method getCode ] { } Method [ final public method getFile ] { } Method [ final public method getLine ] { } Method [ final public method getTrace ] { } Method [ final public method getTraceAsString ] { } Method [ public method __toString ] { } } } ]]> <classname>Reflector</classname> Reflector is an interface implemented by all exportable Reflection classes. ]]> <classname>ReflectionException</classname> ReflectionException extends the standard Exception and is thrown by Reflection API. No specific methods or properties are introduced. <classname>ReflectionFunction</classname> The ReflectionFunction class lets you reverse-engineer functions. ]]> Parent class ReflectionFunctionAbstract has the same methods except invoke, invokeArgs, export and isDisabled. 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. Using the <classname>ReflectionFunction</classname> class The %s function '%s'\n". " declared in %s\n". " lines %d to %d\n", $func->isInternal() ? 'internal' : 'user-defined', $func->getName(), $func->getFileName(), $func->getStartLine(), $func->getEndline() ); // Print documentation comment printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1)); // Print static variables if existant if ($statics = $func->getStaticVariables()) { printf("---> Static variables: %s\n", var_export($statics, 1)); } // Invoke the function printf("---> Invokation results in: "); var_dump($func->invoke()); // you may prefer to use the export() method echo "\nReflectionFunction::export() results:\n"; echo ReflectionFunction::export('counter'); ?> ]]> The method invoke accepts a variable number of arguments which are passed to the function just as in call_user_func. <classname>ReflectionParameter</classname> The ReflectionParameter class retrieves information about a function's or method's parameters. ]]> getDefaultValue, isDefaultValueAvailable and isOptional were added in PHP 5.0.3, while isArray was added in PHP 5.1.0. getDeclaringFunction and getPosition were added in PHP 5.2.3. 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. Using the <classname>ReflectionParameter</classname> class getParameters() as $i => $param) { printf( "-- Parameter #%d: %s {\n". " Class: %s\n". " Allows NULL: %s\n". " Passed to by reference: %s\n". " Is optional?: %s\n". "}\n", $i, // $param->getPosition() can be used from PHP 5.2.3 $param->getName(), var_export($param->getClass(), 1), var_export($param->allowsNull(), 1), var_export($param->isPassedByReference(), 1), $param->isOptional() ? 'yes' : 'no' ); } ?> ]]> <classname>ReflectionClass</classname> The ReflectionClass class lets you reverse-engineer classes and interfaces. ]]> 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. Using the <classname>ReflectionClass</classname> class The %s%s%s %s '%s' [extends %s]\n" . " declared in %s\n" . " lines %d to %d\n" . " having the modifiers %d [%s]\n", $class->isInternal() ? 'internal' : 'user-defined', $class->isAbstract() ? ' abstract' : '', $class->isFinal() ? ' final' : '', $class->isInterface() ? 'interface' : 'class', $class->getName(), var_export($class->getParentClass(), 1), $class->getFileName(), $class->getStartLine(), $class->getEndline(), $class->getModifiers(), implode(' ', Reflection::getModifierNames($class->getModifiers())) ); // Print documentation comment printf("---> Documentation:\n %s\n", var_export($class->getDocComment(), 1)); // Print which interfaces are implemented by this class printf("---> Implements:\n %s\n", var_export($class->getInterfaces(), 1)); // Print class constants printf("---> Constants: %s\n", var_export($class->getConstants(), 1)); // Print class properties printf("---> Properties: %s\n", var_export($class->getProperties(), 1)); // Print class methods printf("---> Methods: %s\n", var_export($class->getMethods(), 1)); // If this class is instantiable, create an instance if ($class->isInstantiable()) { $counter = $class->newInstance(); echo '---> $counter is instance? '; echo $class->isInstance($counter) ? 'yes' : 'no'; echo "\n---> new Object() is instance? "; echo $class->isInstance(new Object()) ? 'yes' : 'no'; } ?> ]]> The method newInstance accepts a variable number of arguments which are passed to the function just as in call_user_func. $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo'). <classname>ReflectionObject</classname> The ReflectionObject class lets you reverse-engineer objects. ]]> <classname>ReflectionMethod</classname> The ReflectionMethod class lets you reverse-engineer class methods. ]]> To introspect a method, you will first have to create an instance of the ReflectionMethod class. You can then call any of the above methods on this instance. Using the <classname>ReflectionMethod</classname> class The %s%s%s%s%s%s%s method '%s' (which is %s)\n" . " declared in %s\n" . " lines %d to %d\n" . " having the modifiers %d[%s]\n", $method->isInternal() ? 'internal' : 'user-defined', $method->isAbstract() ? ' abstract' : '', $method->isFinal() ? ' final' : '', $method->isPublic() ? ' public' : '', $method->isPrivate() ? ' private' : '', $method->isProtected() ? ' protected' : '', $method->isStatic() ? ' static' : '', $method->getName(), $method->isConstructor() ? 'the constructor' : 'a regular method', $method->getFileName(), $method->getStartLine(), $method->getEndline(), $method->getModifiers(), implode(' ', Reflection::getModifierNames($method->getModifiers())) ); // Print documentation comment printf("---> Documentation:\n %s\n", var_export($method->getDocComment(), 1)); // Print static variables if existant if ($statics= $method->getStaticVariables()) { printf("---> Static variables: %s\n", var_export($statics, 1)); } // Invoke the method printf("---> Invokation results in: "); var_dump($method->invoke(NULL)); ?> ]]> Getting closure using <classname>ReflectionMethod</classname> class getMethod('printer'); $closure = $method->getClosure(); /* As of PHP 5.3.0 */ $closure(); // Hello World! ?> ]]> Trying to invoke private, protected or abstract methods will result in an exception being thrown from the invoke method. For static methods as seen above, you should pass NULL as the first argument to invoke. For non-static methods, pass an instance of the class. <classname>ReflectionProperty</classname> The ReflectionProperty class lets you reverse-engineer class properties. ]]> getDocComment was added in PHP 5.1.0. setAccessible was added in PHP 5.3.0. To introspect a property, you will first have to create an instance of the ReflectionProperty class. You can then call any of the above methods on this instance. Using the <classname>ReflectionProperty</classname> class The%s%s%s%s property '%s' (which was %s)\n" . " having the modifiers %s\n", $prop->isPublic() ? ' public' : '', $prop->isPrivate() ? ' private' : '', $prop->isProtected() ? ' protected' : '', $prop->isStatic() ? ' static' : '', $prop->getName(), $prop->isDefault() ? 'declared at compile-time' : 'created at run-time', var_export(Reflection::getModifierNames($prop->getModifiers()), 1) ); // Create an instance of String $obj= new String(); // Get current value printf("---> Value is: "); var_dump($prop->getValue($obj)); // Change value $prop->setValue($obj, 10); printf("---> Setting value to 10, new value is: "); var_dump($prop->getValue($obj)); // Dump object var_dump($obj); ?> ]]> Getting value from private and protected properties using <classname>ReflectionProperty</classname> class setAccessible(true); /* As of PHP 5.3.0 */ var_dump($prop->getValue($obj)); // int(2) $prop = new ReflectionProperty('Foo', 'z'); $prop->setAccessible(true); /* As of PHP 5.3.0 */ var_dump($prop->getValue($obj)); // int(2) ?> ]]> Trying to get or set private or protected class property's values will result in an exception being thrown. <classname>ReflectionExtension</classname> The ReflectionExtension class lets you reverse-engineer extensions. You can retrieve all loaded extensions at runtime using the get_loaded_extensions. ]]> To introspect an extension, you will first have to create an instance of the ReflectionExtension class. You can then call any of the above methods on this instance. Using the <classname>ReflectionExtension</classname> class getName(), $ext->getVersion() ? $ext->getVersion() : 'NO_VERSION', sizeof($ext->getFunctions()), var_export($ext->getFunctions(), 1), sizeof($ext->getConstants()), var_export($ext->getConstants(), 1), sizeof($ext->getINIEntries()), var_export($ext->getINIEntries(), 1), sizeof($ext->getClassNames()), var_export($ext->getClassNames(), 1) ); ?> ]]> Extending the reflection classes In case you want to create specialized versions of the built-in classes (say, for creating colorized HTML when being exported, having easy-access member variables instead of methods or having utility methods), you may go ahead and extend them. Extending the built-in classes visibility = Reflection::getModifierNames($this->getModifiers()); } } /** * Demo class #1 * */ class T { protected function x() {} } /** * Demo class #2 * */ class U extends T { function x() {} } // Print out information var_dump(new My_Reflection_Method('U', 'x')); ?> ]]> Caution: If you're overwriting the constructor, remember to call the parent's constructor _before_ any code you insert. Failing to do so will result in the following: Fatal error: Internal error: Failed to retrieve the reflection object