如何获取参数类型提示的字符串名称? [英] How to get the string name of the argument's type hint?

查看:45
本文介绍了如何获取参数类型提示的字符串名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有这个功能:

Let us say we have this function:

function greetMe (string $name) {                                                                                                                                        
    echo '<br/>'.$name;                                                                                                                                                  
    echo '<br/>'.gettype($name);                                                                                                                                         
}                                                                                                                                                                        

如您所见,我们可以获取参数 $ name 的类型.
现在,我很想知道在此函数的主体内是否有可能知道我声明了 string 类型,而不是其他类型.有提示吗?

As you can see, we can get the type of the parameter $name.
Now I am interested to know if there is a possibility, within the body of this function, to know that I declared the type string and not some other type. Any hints?

推荐答案

在PHP 7和更高版本中,您可以使用 ReflectionParameter.getType .

In PHP 7 and later, you can use ReflectionParameter.getType.

示例1的ReflectionParameter :: getType()示例

Example #1 ReflectionParameter::getType() example

<?php
function someFunction(int $param, $param2) {}

$reflectionFunc = new ReflectionFunction('someFunction');
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
$reflectionType2 = $reflectionParams[1]->getType();

echo $reflectionType1;
var_dump($reflectionType2);

上面的示例将输出类似于:

The above example will output something similar to:

int
null

这篇关于如何获取参数类型提示的字符串名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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