問題描述
我正在嘗試使用 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;
這篇關于PHP 反射 - 獲取方法參數類型為字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!