如何通过反射获取构造函数参数的类型? [英] How do I get the type of constructor parameter via reflection?

查看:400
本文介绍了如何通过反射获取构造函数参数的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在构造函数参数列表上使用类型提示,如下所示:

I'm using type hinting on my constructor parameter list like so:

public function __construct(FooRepository $repository)

是否有一种使用PHP Reflection API来获取提示类型的方法?换句话说,我想要一个反射函数,可以以某种方式调用它来返回字符串"FooRepository".我试过通过反射来获取构造函数,然后再通过构造函数获取参数,但是我看不到任何能给我提示类型字符串的东西.

Is there a way to use the PHP Reflection API to get the hinted type? In other words, I want a reflection function that I can call to somehow get back the string "FooRepository". I've tried getting the constructor via reflection and then getting the parameters if the constructor, but I don't see anything that will give me the string of the hinted type.

推荐答案

尝试一下.

class Foo {
    public function __construct(Bar $test) {
    }
}

class Bar {
    public function __construct() {
    }
}

$reflection = new ReflectionClass('Foo');
$params = $reflection->getConstructor()->getParameters();
foreach ($params AS $param) {
    echo $param->getClass()->name . '<br>';
}

这篇关于如何通过反射获取构造函数参数的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆