Sunday, December 16, 2007

Reflection Class

Since PHP 5 is a set of classes and interfaces that allow us to obtain information about the classes, functions, methods, attributes and objects. This package allows us, for example, to know how many parameters receives a function, and how many are required ... One example of how to use this

/**
* This function repeats
*
* @param string $text
* @param integer $times
*/
function repeat($text, $times = 2) {
return str_repeat($text, $times);
}
$reflection = new ReflectionFunction('repeat');
echo 'User defined: ' , $reflection->isUserDefined() , "\r\n";
echo 'Documentation: ' , $reflection->getDocComment() , "\r\n";
echo '# Params: ' , $reflection->getNumberOfParameters() , "\r\n";
foreach ($reflection->getParameters() as $parametro)
{
echo 'Parameter "' , $parametro->getName() , '" ' , ($parametro->isOptional() ? '' : 'no ') , 'is optional' , "\n";
echo 'By default: ' , ($parametro->isDefaultValueAvailable() ? $parametro->getDefaultValue() : 'doesn\' have any') , "\n";
}
?>

No comments: