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.
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.
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.
Parameterized Constructor – A constructor is called Parameterized Constructor when it accepts a specific number of parameters.
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.
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>'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With