Method "getName" is available when you access getType from getParameters from class reports information of a method(ReflectionMethod).
No need to instantiate the ReflectionNamedType.
Below is my custom method on resolving method dependencies, getName is a big help.
<?php
class A
{
public function my()
{
return ' My ';
}
}
class B
{
public function __construct(A $a)
{
$this->a = $a;
}
public function hello($string)
{
return 'Hello' . $this->a->my() . $string . '.';
}
}
class C
{
public function print($instance, $method)
{
$params = ['World'];
echo call_user_func_array(array($instance, $method), array_merge($this->resolveMethodDependencies($instance, $method), $params));
}
public function instantiate($class)
{
if(method_exists($class, '__construct')) $instance = new $class(...$this->resolveMethodDependencies($class, '__construct'));
else $instance = new $class;
return $instance;
}
protected function resolveMethodDependencies($class, $method)
{
$params = [];
$reflection = new \ReflectionMethod($class, $method);
foreach ($reflection->getParameters() as $param) {
if($type = $param->getType()) {
if(!$type || !$this->instatiatable ($type)) continue;
$className = $type->getName();
if(method_exists($className, '__construct')) {
$params[] = new $className(...$this->resolveMethodDependencies($className, '__construct'));
continue;
}
$params[] = new $className;
}
}
return $params;
}
protected function instatiatable ($type)
{
return $type != 'Closure' && !is_callable($type) && class_exists($type);
}
}
$class = new C;
$class->print(
$class->instantiate('B'), 'hello'
);
Output:
Hello My World.