如何用反射类测试类型提示参数而不出错



测试一个类/方法是否在反射类中有类型暗示参数的正确方法是什么?

如何在不抛出错误的情况下测试它是否存在,是否有类型提示?

到目前为止,如果没有类型提示,则返回通知。

Notice: Trying to get property of non-object in 

(如果我使用)getClass()->getName();

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

这就是你要找的东西

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);
}
输出:

Parameter "command" of type "CommandInterface"
Parameter "when" of type "string"
Parameter "delayed" of type "boolean"
Parameter "append" of type "NULL"

最新更新