Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the type of constructor parameter via reflection?

Tags:

php

reflection

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

public function __construct(FooRepository $repository)

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.

like image 423
TaylorOtwell Avatar asked Nov 24 '10 00:11

TaylorOtwell


People also ask

Which method is used to get constructor using reflection?

The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.

Which method used to fetch the parameter types using method parameter reflection is?

reflect package is used to fetch the parameter types using method parameter reflection. Reflection is a process of analyzing and modifying all capabilities of class at runtime.

What type of constructor it is when it has specific number of parameters?

Parameterized Constructor – A constructor is called Parameterized Constructor when it accepts a specific number of parameters.

How do you find the class name in reflection?

Getting class name using reflection If you want to get the class name using the instance of the Class. As you can see using the method getName() gives you the fully qualified name whereas getSimpleName() method gives you only the class name.


1 Answers

Try this out.

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>'; } 
like image 54
simshaun Avatar answered Oct 06 '22 01:10

simshaun