PHP 反射 - 获取方法参数类型为字符串
我正在尝试使用 PHP 反射根据控制器方法中的参数类型自动动态加载模型的类文件.这是一个示例控制器方法.
I'm trying to use PHP reflection to dynamically load the class files of models automatically based upon the type of parameter that is in the controller method. Here's an example controller method.
<?php
class ExampleController
{
public function PostMaterial(SteelSlugModel $model)
{
//etc...
}
}
这是我目前所拥有的.
//Target the first parameter, as an example
$param = new ReflectionParameter(array('ExampleController', 'PostMaterial'), 0);
//Echo the type of the parameter
echo $param->getClass()->name;
这有效,并且输出将是SteelSlugModel",正如预期的那样.但是,模型的类文件可能尚未加载,并且使用 getClass() 需要定义类 - 我这样做的部分原因是自动加载控制器操作可能需要的任何模型.
This works, and the output would be 'SteelSlugModel', as expected. However, there is the possibility that the class file of the model may not be loaded yet, and using getClass() requires that the class be defined - part of why I'm doing this is to autoload any models that a controller action may require.
有没有办法不用先加载class文件就可以得到参数类型的名字?
Is there a way to get the name of the parameter type without having to load the class file first?
推荐答案
我认为唯一的方法是export
并操作结果字符串:
I think the only way is to export
and manipulate the result string:
$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;
相关文章