Skip to content

Instantly share code, notes, and snippets.

@simshaun
Created June 29, 2012 01:02
Show Gist options
  • Save simshaun/3015038 to your computer and use it in GitHub Desktop.
Save simshaun/3015038 to your computer and use it in GitHub Desktop.
Using reflection to obtain method signatures
<?php
/**
* Necessary because $param->getClass() requires the class to be loaded.
* We don't want to have to load every class.
*/
function getClassName(ReflectionParameter $param) {
preg_match('/\[\s\<\w+?>\s([\w]+)/s', $param->__toString(), $matches);
return isset($matches[1]) ? $matches[1] : null;
}
interface Vehicle {
/**
* I'm a docblock!
*/
public function setColor(Color $color, $foo = 'foo');
public function setWeight(UnitOfWeight $weight);
}
// ------ //
echo PHP_EOL . '--------------------------------------------------------' . PHP_EOL;
$reflection = new ReflectionClass('Vehicle');
foreach ($reflection->getMethods() as $method)
{
echo PHP_EOL . '-------------' . PHP_EOL;
$docBlock = $method->getDocComment();
$modifiers = implode(' ', Reflection::getModifierNames($method->getModifiers()));
$name = $method->name;
$params = array();
foreach ($method->getParameters() as $param)
{
$className = getClassName($param);
$sig = ! empty($className) ? $className . ' ' : null;
$sig .= '$' . $param->name;
if ($param->isOptional())
{
$sig .= ' = ' . $param->getDefaultValue();
}
$params[] = $sig;
}
echo ! empty($docBlock) ? $docBlock . PHP_EOL : null;
echo ! empty($modifiers) ? $modifiers . ' ' : null;
echo "function $name" . '(' . implode(', ', $params) . ')';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment