/*
* First: Some basics about reflection using a sample class. This is
* not advance, only shows the class name and some information:
*/
require_once "reflector.class.php";
$reflector = new ReflectionClass("ReflectorExample");
echo "Class name: ".$reflector->getName()."\n";
echo "Defined in file: ".$reflector->getFileName()."\n";
echo "Between lines: ".$reflector->getStartLine()." and ".$reflector->getEndLine()."\n";
/*
* Now real reflection magic. We implement our own versions of:
* - get_class => my_get_class
* - get_class_methods => my_get_class_methods
* - function_exists => my_function_exists
*
* And a function that retrieves the supported parameters for
* a given function:
* - my_get_function_parameters
*
* Here are placed the output of that functions, so see below
* to read the commented code :-).
*/
/* Get a class name using an instance: */
$my_class = new ReflectorExample();
$classname = my_get_class($my_class);
echo "Classname of \$my_class: $classname\n";
/* Get the class methods */
foreach (my_get_class_methods("ReflectorExample") as $method) {
echo "method found: $method\n";
}
/* Dumps some function parameters: */
foreach (my_function_get_parameters("sprintf") as $parameter) {
echo "Parameter: $parameter\n";
}
/* Shows if functions var_dump, sprintf and foobar are defined: */
$funcs = array("var_dump", "sprintf", "foobar");
foreach ($funcs as $func) {
$exists = my_function_exists($func) ? "yes" : "no";
echo "function $func exists: $exists\n";
}
function my_get_class($instance)
{
$reflector = new ReflectionObject($instance);
if (!$reflector->isInstance($instance))
return false;
return $reflector->getName();
}
function my_get_class_methods($classname)
{
$methods = array();
if (!class_exists($classname))
throw new Exception ("Class $classname does not exists.");
$reflector = new ReflectionClass($classname);
$reflected_methods = $reflector->getMethods();
foreach ($reflected_methods as $reflected)
$methods[] = $reflected->getName();
return $methods;
}
function my_function_exists($function)
{
try {
$reflector = new ReflectionFunction($function);
} catch (ReflectionException $e) {
return false;
}
return true;
}
function my_function_get_parameters($function)
{
if (!my_function_exists($function))
throw new Exception ("Specified function $function does not exists.");
$reflector = new ReflectionFunction($function);
foreach ($reflector->getParameters() as $parameter)
$parameters[] = $parameter->name;
return $parameters;
}
?>
reflector.class.php
<?php
class ReflectorExample
{
public function __construct()
{
}
public function exampleFunction($parameter1)
{
}
}