问题
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