user1502826
user1502826

Reputation: 583

Extract type hint from ReflectionParameter

class C 
{
    function methodA(Exception $a, array $id){}
}

function getClassName(ReflectionParameter $param) {
    $regex = '/\[([^\]]*)\]/';
    preg_match($regex, $param->__toString(), $matches);
    return isset($matches[1]) ? $matches[1] : null;
}

foreach( new ReflectionMethod('C', 'methodA')->getParameters() as $param)
{
    echo getClassName($param);
}

Want returned value to simply be 'Exception' and 'array' not "Exception $a" and "array $id". What should the regex be. Working on php 5.3

Upvotes: 0

Views: 101

Answers (1)

Alfwed
Alfwed

Reputation: 3282

Just use the Reflection classes

foreach( (new ReflectionMethod('C', 'methodA'))->getParameters() as $param)
{
    $class = $param->getClass();
    if ($class) {
        echo $class->getName()."\n";
    } elseif ($param->isArray()) {
        echo "array\n";
    }  else {
        echo "unknown\n";
    }
}

Upvotes: 1

Related Questions