【问题标题】:How to get the string name of the argument's type hint?如何获取参数类型提示的字符串名称?
【发布时间】:2019-01-24 03:51:23
【问题描述】:

假设我们有这个功能:

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

如您所见,我们可以得到参数$name的类型。
现在我很想知道在这个函数的主体中是否有可能知道我声明了类型string而不是其他类型。有什么提示吗?

【问题讨论】:

  • gettype 不是你要找的东西,你已经在那里了
  • 不,我不是在寻找gettype($argument),我希望能够访问string 类型(我处于需要此信息以满足特定需求的情况)跨度>
  • @Ghost 考虑function greetMe(Foo $foo)class Bar extends Foo 的情况,其中函数用作greetMe(aBar)。然后,gettype 将返回 Bar,即使类型提示是 Foo

标签: php function types


【解决方案1】:

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

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

<?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);

上面的例子会输出类似于:

int
null

【讨论】:

  • 这正是我所需要的。谢谢。
  • @BillalBEGUERADJ 你的意思是这样的吗? 3v4l.org/Vnf5E 刚刚用谷歌搜索它,它很容易获得(不是答案,而是反射类本身)
  • 是的,ReflectionParameter.getType 是我问题的关键答案,谢谢@Ghost
  • @BillalBEGUERADJ 很高兴这能有所启发,别忘了接受 vulcan 的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-10-18
  • 1970-01-01
  • 2017-06-13
  • 2014-08-06
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
相关资源
最近更新 更多