PHP反射-以字符串形式获取方法参数类型 [英] PHP Reflection - Get Method Parameter Type As String
问题描述
我正在尝试使用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...
}
}
这是我到目前为止所拥有的.
Here's what I have so far.
//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.
是否有一种无需首先加载类文件即可获取参数类型名称的方法?
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;
这篇关于PHP反射-以字符串形式获取方法参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!