1

What is the proper way to test if a class/method has a type hinted parameter with the reflection class.

How can I test if it exists, is type hinted or not without throwing errors.

What I have sofar returns a notice if it is not type hinted.

Notice: Trying to get property of non-object in 

(if I use) getClass()->getName();

 $p = new ReflectionParameter(array(get_called_class(), $method), 0);
    if ($p) { // not working
        echo "param exists"; 

1 Answer 1

0

This is what are you looking for ?

interface CommandInterface
{
}

class Dummy
{
    public function execute(
        CommandInterface $command,
        $when = 'now',
        $delayed = true,
        $append = null
    ) {
        //
    }
}

$reflector = new \ReflectionClass('Dummy');
foreach($reflector->getMethod('execute')->getParameters() as $param)
{
    $type = ($param->getClass()) ?
        $param->getClass()->name :
        gettype($param->getDefaultValue());

    echo sprintf('Parameter "%s" of type "%s"'.PHP_EOL, $param->getName(), $type);
}

Output:

Parameter "command" of type "CommandInterface"
Parameter "when" of type "string"
Parameter "delayed" of type "boolean"
Parameter "append" of type "NULL"
1
  • this looks like a sound implementation so I can close this question. I used the shortcut @ to suppress the warning if it's not a class,but if your code does not need it, it is definitivly better.
    – Richard
    May 22, 2014 at 9:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.