PHP反射 - 获取方法参数类型为字符串

Jar*_*les 12 php reflection

我正在尝试使用PHP反射根据控制器方法中的参数类型自动动态加载模型的类文件.这是一个示例控制器方法.

<?php

class ExampleController
{
    public function PostMaterial(SteelSlugModel $model)
    {
        //etc...
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所拥有的.

//Target the first parameter, as an example
$param = new ReflectionParameter(array('ExampleController', 'PostMaterial'), 0);

//Echo the type of the parameter
echo $param->getClass()->name;
Run Code Online (Sandbox Code Playgroud)

这是有效的,输出将是'SteelSlugModel',如预期的那样.但是,有可能模型的类文件可能尚未加载,并且使用getClass()要求定义类 - 为什么我这样做的一部分是自动加载控制器操作可能需要的任何模型.

有没有办法获取参数类型的名称,而无需先加载类文件?

小智 11

我想这就是你要找的东西:

class MyClass {

    function __construct(AnotherClass $requiredParameter, YetAnotherClass $optionalParameter = null) {
    }

}

$reflector = new ReflectionClass("MyClass");

foreach ($reflector->getConstructor()->getParameters() as $param) {
    // param name
    $param->name;

    // param type hint (or null, if not specified).
    $param->getClass()->name;

    // finds out if the param is required or optional
    $param->isOptional();
}
Run Code Online (Sandbox Code Playgroud)


net*_*der 10

我认为唯一的方法是export操纵结果字符串:

$refParam = new ReflectionParameter(array('Foo', 'Bar'), 0);

$export = ReflectionParameter::export(
   array(
      $refParam->getDeclaringClass()->name, 
      $refParam->getDeclaringFunction()->name
   ), 
   $refParam->name, 
   true
);

$type = preg_replace('/.*?(\w+)\s+\$'.$refParam->name.'.*/', '\\1', $export);
echo $type;
Run Code Online (Sandbox Code Playgroud)


mas*_*tic 5

getType从 PHP 7.0 开始可以使用该方法。

class Foo {}
class Bar {}

class MyClass
{
    public function baz(Foo $foo, Bar $bar) {}
}

$class = new ReflectionClass('MyClass');
$method = $class->getMethod('baz');
$params = $method->getParameters();

var_dump(
    'Foo' === (string) $params[0]->getType()
);
Run Code Online (Sandbox Code Playgroud)