【问题标题】:There is option to get expected type of variable in PHP? [duplicate]可以选择在 PHP 中获取预期类型的​​变量吗? [复制]
【发布时间】:2020-05-22 05:06:57
【问题描述】:

我有使用

将数组转换为对象的方法
$class = get_class($object);
$methodList = get_class_methods($class);

但现在我也需要有关预期变量类型的信息。例如从这个方法:

public function setFoo(int $foo)
{
}

我也需要得到int。有什么办法可以得到吗?

【问题讨论】:

标签: php php-7.2


【解决方案1】:

您可以使用Reflection。特别是ReflectionParameter::getType()

function someFunction(int $param, $param2) {}

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

assert($reflectionType1 instanceof ReflectionNamedType);
echo $reflectionType1->getName(), PHP_EOL;
var_dump($reflectionType2);

上面的例子会输出:

int
NULL

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    相关资源
    最近更新 更多