How to get the string name of the argument's type hint?

故事扮演 提交于 2021-02-05 08:36:05

问题


Let us say we have this function:

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

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?


回答1:


In PHP 7 and later, you can use 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


来源:https://stackoverflow.com/questions/51889701/how-to-get-the-string-name-of-the-arguments-type-hint

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!