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 class Reflection { } interface Reflector { } class ReflectionException extends Exception { } class ReflectionFunction implements Reflector { } class ReflectionParameter implements Reflector { } class ReflectionMethod extends ReflectionFunction { } class ReflectionClass implements Reflector { } class ReflectionObject extends ReflectionClass { } class ReflectionProperty implements Reflector { } class ReflectionExtension implements Reflector { } ?>
Notã:
For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
The ReflectionFunction class lets you
reverse-engineer functions.
<?php class ReflectionFunction implements Reflector { public object __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public mixed invoke(mixed* args) public bool returnsReference() public ReflectionParameter[] getParameters() } ?>
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.
Exemplu 14-8. Using the ReflectionFunction class
<?php /** * A simple counter * * @return int */ function counter() { static $c = 0;
return $c++; }
// Create an instance of the Reflection_Function class $func = new ReflectionFunction('counter');
// Print out basic information printf( "===> 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() );
The ReflectionParameter class retrieves
information about a function's or method's parameters.
<?php class ReflectionParameter implements Reflector { public object __construct(string name) public string __toString() public static string export() public string getName() public ReflectionClass getClass() public bool allowsNull() public bool isPassedByReference() } ?>
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.
Exemplu 14-9. Using the ReflectionParameter class
<?php function foo($a, $b, $c) { } function bar(Exception $a, &$b, $c) { } function baz($a = 1, $b = NULL, ReflectionFunction $c) { } function abc() { }
// Create an instance of Reflection_Function with the // parameter given from the command line. $reflect = new ReflectionFunction($argv[1]);
The ReflectionClass class lets
you reverse-engineer classes.
<?php class ReflectionClass implements Reflector { public __construct(string name) public string __toString() public static string export() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public ReflectionMethod getConstructor() public ReflectionMethod getMethod(string name) public ReflectionMethod[] getMethods() public ReflectionProperty getProperty(string name) public ReflectionProperty[] getProperties() public array getConstants() public mixed getConstant(string name) public bool isInstantiable() public bool isInterface() public bool isFinal() public bool isAbstract() public int getModifiers() public bool isInstance(stdclass object) public stdclass newInstance(mixed* args) public ReflectionClass[] getInterfaces() public ReflectionClass getParentClass() public bool isSubclassOf(ReflectionClass class) } ?>
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.
Exemplu 14-10. Using the ReflectionClass class
<?php interface Serializable { // ... }
class Object { // ... }
/** * A counter class * */ class Counter extends Object implements Serializable { const START = 0; private static $c = Counter::START;
/** * Invoke counter * * @access public * @return int */ public function count() { return self::$c++; } }
// Create an instance of the ReflectionClass class $class= new ReflectionClass('Counter');
// Print out basic information printf( "===> 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())) );
The ReflectionMethod class lets you
reverse-engineer class methods.
<?php class ReflectionMethod extends ReflectionFunction { public __construct(mixed class, string name) public static string export() public mixed invoke(stdclass object, mixed* args) public bool isFinal() public bool isAbstract() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isConstructor() public int getModifiers() public ReflectionClass getDeclaringClass()
/* Inherited from ReflectionFunction */ public string __toString() public string getName() public bool isInternal() public bool isUserDefined() public string getFileName() public int getStartLine() public int getEndLine() public string getDocComment() public array getStaticVariables() public bool returnsReference() public ReflectionParameter[] getParameters() } ?>
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.
Exemplu 14-11. Using the ReflectionMethod class
<?php class Counter { private static $c = 0;
/** * Increment counter * * @final * @static * @access public * @return int */ final public static function increment() { self::$c++; return self::$c; } }
// Create an instance of the Reflection_Method class $method= new ReflectionMethod('Counter', 'increment');
// Print out basic information printf( "===> 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())) );
The ReflectionProperty class lets you
reverse-engineer class properties.
<?php class ReflectionProperty implements Reflector { public __construct(mixed class, string name) public string __toString() public static string export() public string getName() public bool isPublic() public bool isPrivate() public bool isProtected() public bool isStatic() public bool isDefault() public int getModifiers() public mixed getValue(stdclass object) public void setValue(stdclass object, mixed value) public ReflectionClass getDeclaringClass() } ?>
To introspect a method, you will first have to create an instance
of the ReflectionProperty class. You can then
call any of the above methods on this instance.
Exemplu 14-12. Using the ReflectionProperty class
<?php class String { public $length = 5; }
// Create an instance of the ReflectionProperty class $prop = new ReflectionProperty('String', 'length');
// Print out basic information printf( "===> 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); ?>
Notã:
Trying to get or set private or protected class property's values
will result in an exception being thrown.
The ReflectionExtension class lets you
reverse-engineer extensions. You can retrieve all loaded extensions
at runtime using the get_loaded_extensions().
<?php class ReflectionExtension implements Reflector { public __construct(string name) public string __toString() public static string export() public string getName() public string getVersion() public ReflectionFunction[] getFunctions() public array getConstants() public array getINIEntries() } ?>
To introspect a method, you will first have to create an instance
of the ReflectionProperty class. You can then call
any of the above methods on this instance.
Exemplu 14-13. Using the ReflectionExtension class
<?php // Create an instance of the ReflectionProperty class $ext = new ReflectionExtension('standard');
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.
Exemplu 14-14. Extending the built-in classes
<?php /** * My Reflection_Method class * */ class My_Reflection_Method extends ReflectionMethod { public $visibility= '';
public function __construct($o, $m) { parent::__construct($o, $m); $this->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')); ?>
Notã:
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