PHP : Language Reference : Classes and Objects (PHP 5) : Reflection
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:
Note:
For details on these classes, have a look at the next chapters.
If we were to execute the code in the example below:
Example 10.33. Basic usage of the reflection API
<?php
Reflection::export(new ReflectionClass('Exception')); ?>
The above example will output:
Class [ <internal> class Exception ] {
- Constants [0] {
}
- Static properties [0] {
}
- Static methods [0] {
}
- Properties [6] {
Property [ <default> protected $message ]
Property [ <default> private $string ]
Property [ <default> protected $code ]
Property [ <default> protected $file ]
Property [ <default> protected $line ]
Property [ <default> private $trace ]
}
- Methods [9] {
Method [ <internal> final private method __clone ] {
}
Method [ <internal> <ctor> public method __construct ] {
- Parameters [2] {
Parameter #0 [ <required> $message ]
Parameter #1 [ <required> $code ]
}
}
Method [ <internal> final public method getMessage ] {
}
Method [ <internal> final public method getCode ] {
}
Method [ <internal> final public method getFile ] {
}
Method [ <internal> final public method getLine ] {
}
Method [ <internal> final public method getTrace ] {
}
Method [ <internal> final public method getTraceAsString ] {
}
Method [ <internal> public method __toString ] {
}
}
}
Reflector is an interface implemented by all
exportable Reflection classes.
ReflectionException extends the standard Exception and is thrown by Reflection
API. No specific methods or properties are introduced.
The ReflectionFunction class lets you
reverse-engineer functions.
Parent class ReflectionFunctionAbstract has the
same methods except invoke(),
invokeArgs(), export() and
isDisabled().
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 10.34. 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()
);
// 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'); ?>
Note:
The method invoke() accepts a variable number of
arguments which are passed to the function just as in
call_user_func().
The ReflectionParameter class retrieves
information about a function's or method's parameters.
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 10.35. Using the ReflectionParameter class
<?php function foo($a, $b, $c) { }
function bar(Exception $a, &$b, $c) { }
function baz(ReflectionFunction $a, $b = 1, $c = null) { }
function abc() { }
// Create an instance of Reflection_Function with the
// parameter given from the command line. $reflect = new ReflectionFunction($argv[1]);
echo $reflect;
foreach ($reflect->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->getName(),
var_export($param->getClass(), 1),
var_export($param->allowsNull(), 1),
var_export($param->isPassedByReference(), 1),
$param->isOptional() ? 'yes' : 'no'
);
} ?>
The ReflectionClass class lets
you reverse-engineer classes.
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 10.36. 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()))
);
// 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';
} ?>
Note:
$class = new ReflectionClass('Foo'); $class->isInstance($arg)
is equivalent to $arg instanceof Foo or
is_a($arg, 'Foo') .
The ReflectionObject class lets
you reverse-engineer objects.
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.
Example 10.37. Using the ReflectionMethod class
<?php class Counter {
private static $c = 0;
/**
* Increment counter
*
* @final
* @static
* @access public
* @return int
*/
final public static function increment()
{
return ++self::$c;
}
}
// Create an instance of the ReflectionMethod 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()))
);
// 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)); ?>
Note:
Trying to invoke private, protected or abstract methods will result
in an exception being thrown from the invoke()
method.
Note:
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.
The ReflectionProperty class lets you
reverse-engineer class properties.
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.
Example 10.38. 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); ?>
Note:
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().
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.
Example 10.39. Using the ReflectionExtension class
<?php // Create an instance of the ReflectionProperty class $ext = new ReflectionExtension('standard');
// Print out basic information printf(
"Name : %s\n" .
"Version : %s\n" .
"Functions : [%d] %s\n" .
"Constants : [%d] %s\n" .
"INI entries : [%d] %s\n" .
"Classes : [%d] %s\n",
$ext->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.
Example 10.40. Extending the built-in classes
<?php /**
* My Reflection_Method class
*/ class My_Reflection_Method extends ReflectionMethod {
public $visibility = array();
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')); ?>
Note:
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
russ dot collier
While this is probably obvious to many people (it wasn't to me ;-P), the ReflectionClass::getProperties() method does _NOT_ return inherited properties when reflecting subclasses.
rog_per
Two different scenaria returning an id:
$rc = new ReflectionClass("classExample");
$obj = $rc->newInstanceArgs($request->params);
1. classExample with a __construct() constructor
$obj is NOT the object id!!!
2. classExample with a classExample() constructor
$obj IS the object id
Must be a bug as far as I can see.
walter dot huijbers
The wonderfull example code of russ collier works great until using it in combination with an interface or another abstract class, wich forces to define a function or variable in the loadable dynamic class, and the loaded class doesn't implement all the abstract functions. Ofcourse the class should not be used and an error should be reported, but the reported error is a Fatal error and is impossible to catch. This way it is impossible to, for example, generate an error message displaying the name of the file from wich the class is loaded.
Having dynamicly loadable classes with a forced interface can be very usefull when working on big projects or giving third parties the ability to provide new plugins. Considering this (imho) it would be nice to provide a clean error message to the writer of the plugin.
Please correct me if I'm wrong.
killgecnofspam
Signature of constructor of ReflectionParameter correctly is:
public function __construct(array/string $function, string $name);
where $function is either a name of a global function, or a class/method name pair.
luigi bai
Note: $class = new ReflectionClass('Foo'); $class->isInstance($arg) is equivalent to $arg instanceof Foo or is_a($arg, 'Foo').
This is not correct. Consider the following code:
class A {
}
class C extends A {
}
$rc = new ReflectionClass("C");
$ra = new ReflectionClass("A");
$cc = $rc->newInstance();
$ca = $ra->newInstance();
print("Is? A ".($ra->isInstance($ca)?"true":"false").", but instanceof: ".(($ca instanceof A)?"true":"false")."\n");
print("Is? C ".($ra->isInstance($cc)?"true":"false").", but instanceof: ".(($cc instanceof A)?"true":"false")."\n");
russ dot collier
If you've ever wanted to do dynamic class loading in PHP5, especially when the class you're trying to dynamically load is a Singleton (and therefore you cannot use the new operator), you can do something like this example below, using the PHP5 Reflection API:
<?php
abstract class Shape
{
static public function makeShape( $shapeName )
{
$shapeInstance = null;
$shapeClass = new ReflectionClass( $shapeName );
$shapeMethod = $shapeClass->getMethod( 'getInstance' );
$shapeInstance = $shapeMethod->invoke( null );
$shapeClass = null;
$shapeMethod = null;
return $shapeInstance;
}
abstract public function doStuff();
}
class Triangle extends Shape
{
private static $instance = null;
private function __construct() { }
public static function getInstance()
{
if ( null == self::$instance )
{
self::$instance = new self;
}
return self::$instance;
}
public function doStuff() { }
}
$typeOfShape = 'Triangle';
$shape = null;
try
{
$shape = Shape::makeShape( $typeOfShape );
}
catch ( Exception $e )
{
print "Error creating shape '$typeOfShape'! " . $e->getMessage() . "\n";
}
if ( null != $shape )
{
// $shape will be an instance of Triangle
$shape->doStuff();
}
?>
So by changing the value of $typeOfShape you can dynamically load the appropriate Shape subclass at runtime, thus facilitating a sort of plug-in style architecture for your classes. You can just drop in new Shape subclasses and not have to modify any of the Shape class code to support them in its factory method makeShape() :-)
If your subclasses are all in separate files, you could even make the 'including' of these files dynamic as well, by adding these lines to the Shape::makeShape() method after the $shapeInstance is initialized:
<?php
ini_set( 'include_path', ini_get( 'include_path' ) . PATH_SEPARATOR .
'/path/to/your/php/class/include/files' );
/**
* Assuming your subclasses are in files called 'class_$shapeName.php' :-)
* Of course doing a dynamic require() could be a security problem depending
* on how you validate/clean your $shapeName method parameter (if at all ;-))
*/
require_once( "class_$shapeName.php" );
?>
thiago_mata
If you need to try to do something with the phpdoc or like the java notations in php4, you can create your own
'reflection functions'. This is a litle example of that.
<?php
/**
* Comment used to start a phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'START_DOC' , '/**' );
/**
* Comment used to end a phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'END_DOC' , '*/' );
/**
* Comment used to indicate a tag of phpdoc
* @author Thiago Mata
* @package notations
*/
define( 'TAG_DOC' , '@' );
/**
* This is a function maded in PHP4 to get the notations from some php file.
* Can use comments with many lines
*
* @author Thiago Mata
* @date 05/09/2006
* @package notations
* @param string $strFile
* @copyright open source
* @example <code> $arrNotations = getFileNotations( 'somefile.php' ); </code>
*/
function getFileNotations( $strFile )
{
$strText = file_get_contents( $strFile );
$arrText = explode( "\n" , $strText );
$arrNotations = array();
for ( $intCount = 0 ; $intCount < count( $arrText ) ; ++$intCount )
{
$strLine = $arrText[ $intCount ];
// inside the phpdoc //
if ( strpos( trim( $strLine ) , START_DOC ) === 0 )
{
++$intCount;
$strLine = $arrText[ $intCount ];
$arrNotation = array();
// while the phpdoc is not finished //
while ( ( strpos( trim( $strLine ) , END_DOC ) !== 0 ) and ( $intCount < count( $arrText ) ) )
{
// removing the tag doc from the line //
$strLine = substr( $strLine , strpos( $strLine , TAG_DOC ) );
// get the name of the tag //
$strName = substr( $strLine , 0 , strpos( $strLine , ' ' ) );
// get the value of the tag //
$strLine = substr( $strLine , strpos( $strLine , ' ' ) + 1 );
if ( strpos( trim( $strLine ) , '*' ) === 0 )
{
$strLine = substr( $strLine , strpos( $strLine , '*' ) + 1 );
}
$strLine = trim( $strLine );
if ( ! isset( $arrNotation[ $strName ] ) )
{
$arrNotation[ $strName ] = '';
}
else
{
if ( $strLine != '' )
{
$arrNotation[ $strName ] .= "\n";
}
}
$arrNotation[ $strName ] .= trim( $strLine );
++$intCount;
$strLine = $arrText[ $intCount ];
}
if ( $intCount < count( $arrText ) )
{
do
{
++$intCount;
$strLine = $arrText[ $intCount ];
}
while ( $strLine == '' );
// adding the notation to the next command line //
$arrNotations[ trim( $arrText[ $intCount ] ) ] = $arrNotation;
$intCount--;
}
}
}
return( $arrNotations );
}
print( '<pre>' . "\n" );
var_export( getFileNotations( __FILE__ ) );
print( '</pre>' . "\n" );
?>
<!-- OUTPUT
array (
'define( \'START_DOC\' , \'/**\' );' =>
array (
'' => 'Comment used to start a phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'define( \'END_DOC\' , \'*/\' );' =>
array (
'' => 'Comment used to end a phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'define( \'TAG_DOC\' , \'@\' );' =>
array (
'' => 'Comment used to indicate a tag of phpdoc',
'@author' => 'Thiago Mata',
'@package' => 'notations',
),
'function getFileNotations( $strFile )' =>
array (
'' => 'This is a function maded in PHP4 to get the notations from some php file.
Can use comments with many lines',
'@author' => 'Thiago Mata',
'@date' => '05/09/2006',
'@package' => 'notations',
'@param' => 'string $strFile',
'@copyright' => 'open source',
'@example' => '<code> $arrNotations = getFileNotations( \'somefile.php\' ); </code>',
),
)
-->
will mason
If you are looking for the long $filters for ReflectionClass::getMethods(), here they are. They took me a long time to find. Found nothing in the docs, nor google. But of course, Reflection itself was the final solution, in the form of ReflectionExtension::export("Reflection").
<?php
//The missing long $filter values!!!
ReflectionMethod::IS_STATIC;
ReflectionMethod::IS_PUBLIC;
ReflectionMethod::IS_PROTECTED;
ReflectionMethod::IS_PRIVATE;
ReflectionMethod::IS_ABSTRACT;
ReflectionMethod::IS_FINAL;
//Use them like this
$R = new ReflectionClass("MyClass");
//print all public methods
foreach ($R->getMethods(ReflectionMethod::IS_PUBLIC) as $m)
echo $m->__toString();
?>
salsi
I think all the "final private" methods should be made simply "private", or maybe they might be dropped at all from the declarations.
Some __construct() methods are reported to return something, but actually they should return "void".
no dot prob
I have written a function which returns the value of a given DocComment tag.
Full example:
<?php
header('Content-Type: text/plain');
class Example
{
/**
* This is my DocComment!
*
* @DocTag: prints Hello World!
*/
public function myMethod()
{
echo 'Hello World!';
}
}
function getDocComment($str, $tag = '')
{
if (empty($tag))
{
return $str;
}
$matches = array();
preg_match("/".$tag.":(.*)(\\r\\n|\\r|\\n)/U", $str, $matches);
if (isset($matches[1]))
{
return trim($matches[1]);
}
return '';
}
$method = new ReflectionMethod('Example', 'myMethod');
// will return Hello World!
echo getDocComment($method->getDocComment(), '@DocTag');
?>
Maybe you can add this functionality to the getDocComment methods of the reflection classes.
massimo
I found these limitations using class ReflectionParameter from ReflectionFunction with INTERNAL FUNCTIONS (eg print_r, str_replace, ... ) :
1. parameter names don't match with manual: (try example 19.35 with arg "call_user_func" )
2. some functions (eg PCRE function, preg_match etc) have EMPTY parameter names
3. calling getDefaultValue on Parameters will result in Exception "Cannot determine default value for internal functions"
codeduck
Beware, the Reflection reflects only the information right after compile time based on the definitions, not based on runtime objects. Might be obvious, wasn't for me, until the app throws the exception at my head.
Example:
<?php
class A {
public $a = null;
function set() {
$this->foo = 'bar';
}
}
$a = new A;
$a->set();
// works fine
$Reflection = new ReflectionProperty($a, 'a');
// throws exception
$Reflection = new ReflectionProperty($a, 'foo');
?>
dave
answer to [russ dot collier at gmail dot com]:
ReflectionClass::getProperties() method _DOES_ return inherited properties when reflecting subclasses. Only private properties of subclasses are hidden (of course). And ReflectionClass::getMethods() _DOES_ returns inherited methods.
russ dot collier
Actually, aside from my inconsistent order of keywords in the 2 factory methods ;-) the Triangle::getInstance() method has 1 glaring flaw: it never actually sets the Triangle::$instance property. The correct way to implement a Singleton this way would be to replace Triangle::getInstance() with this:
<?php
static public function getInstance()
{
if ( null == self::$instance )
{
self::$instance = new self;
return self::$instance;
}
return self::$instance;
}
?>
|
|