使用反射获取参数的类型


Get type of parameter with Reflection

我使用以下代码从类中获取方法:

$reflector = new 'ReflectionClass ( $className );
$methods = $reflector->getMethods(ReflectionMethod::IS_PUBLIC);
print_r ( $methods[0] );

那么我从中得到的就是属性的name。但我也对房产类型感兴趣。我怎样才能得到这些信息?

您可以通过执行以下操作来实现:

$params = $methods[0]->getParameters();
$params[0]->getClass()->name;

只有当参数是强类型的时,才能使用getClass()->name

// get the list of parameters
$params = $methods[0]->getParameters();
foreach($params as $param){
  if($param->isArray()){
    // array...
  }else{
    // something else...    
    try{
      $paramClass = $param->getClass();
      if($paramClass !== null){
        // it's a required class ($paramClass->name)
        // note that the class must be loaded at this point
      }
    }catch('Exception $e){
    }
  }
}

这些是您可以通过反射检测到的唯一参数提示。