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

PHP Reflection - Get Method Parameter Type As String(PHP 反射 - 获取方法参数类型为字符串)
本文介绍了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;

这篇关于PHP 反射 - 获取方法参数类型为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Why can#39;t I update data in an array with foreach loop?(为什么我不能用 foreach 循环更新数组中的数据?)
Foreach for arrays inside of an array(Foreach 用于数组内的数组)
PHP array get next key/value in foreach()(PHP 数组在 foreach() 中获取下一个键/值)
Using preg_match on a multidimensional array to return key values arrays(在多维数组上使用 preg_match 返回键值数组)
php foreach as key, every two number as a group(php foreach 为key,每两个数字为一组)
Treat a PHP class that implements Iterator as an array(将实现 Iterator 的 PHP 类视为数组)