略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: ReflectionNamedType::getName

2024-11-22

ReflectionNamedType::getName

(PHP 7 >= 7.1.0, PHP 8)

ReflectionNamedType::getName以字符串形式获取类型的名称

说明

public ReflectionNamedType::getName(): string

参数

此函数没有参数。

返回值

返回被反射的类型的名称。

参见

add a noteadd a note

User Contributed Notes 1 note

up
0
e3jeremy at gmail dot com
3 years ago
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;

               
// This is the right way to get the class name in string.
               
$className = $type->getName();

               
// This will throw error.
                // $className = $param->getType();

                // Alos this one will do the trick.
                // $className = (string) $param->getType();

               
if(method_exists($className, '__construct')) {
                   
$params[] = new $className(...$this->resolveMethodDependencies($className, '__construct'));
                    continue;
                }

               
$params[] = new $className;
            }
        }
        return
$params;
    }

    protected function
instatiatable ($type)
    {
       
// Add conditon if something is leftout.
        // This is to ensure that the type is existing class.
       
return $type != 'Closure' && !is_callable($type) && class_exists($type);
    }
}

$class = new C;

$class->print(
   
$class->instantiate('B'), 'hello'
);

Output:
Hello My World.

官方地址:https://www.php.net/manual/en/reflectionnamedtype.getname.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3