PHP Reflection

Jul 13, 2009 Author: City Hall

With PHP's new object model comes the Reflection API a collection of functions and objects that allows you to examine the contents of a script's code, such as functions and objects, at runtime. Reflection can be very handy in a number of circumstances; for example, it can be used to generate simple documentation, or for determining whether certain functionality is available to a script, and so on. Here's an example:


<?php
/**
* Say Hello
*
* @param string $to
*/
function hello($to = "World")
{
echo "Hello $to";
}
$funcs = get_defined_functions();
?>
<h1>Documentation</h1>
<?php
/**
* Do Foo
*
* @param string $bar Some Bar
* @param array $baz An Array of Baz
*/
function foo($bar, $baz = array()) { }

$funcs = get_defined_functions();
foreach ($funcs['user'] as $func) {
try {
$func = new ReflectionFunction($func);

} catch (ReflectionException $e) {
// ...
}
$prototype = $func->name . ' ( ';
$args = array();
foreach ($func->getParameters() as $param) {
$arg = '';
if ($param->isPassedByReference()) {
$arg = '&';
}
if ($param->isOptional()) {
$arg = '[' .$param->getName(). ' = ' .$param->getDefaultValue(). ']';
} else {
$arg = $param->getName();
}
$args[] = $arg;
}
$prototype .= implode(", ", $args) . ' )';
echo "<h2>$prototype</h2>";
echo "
<p>
Comment:
</p>
<pre>
" .$func->getDocComment(). "
</pre>
<p>
File: " .$func->getFileName(). "
<br />
Lines: " .$func->getStartLine(). " - " .$func->getEndLine(). "
</p>";
}
?>
Comment:
</p>
<pre>
/**
* Say Hello
*
* @param string $to
*/
</pre>
<p>
File: PHPDocument2
<br />
Lines: 13 - 17
</p>

The Reflection API is extremely powerful, since it allows you to inspect both userdefined and internal functions, classes and objects, aswell as extensions. In addition to inspecting them, you can also call functions and methods directly through the API.

tags:

views 2912
  1. Add New Comment