Question

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"; 
Was it helpful?

Solution

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"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top