首页 > 解决方案 > 检查可调用是否可以接收类作为php中的参数

问题描述

我有一个可调用对象$f,我想知道它是否可以接收某个类的实例Foo作为输入。

目前我正在做类似的事情

try {
    $f($foo);
} catch (\TypeError $e) {
    throw new \InvalidArgumentException('The provided function can not evaluate inputs of this type');
}

有没有办法在不实际调用可调用对象的情况下进行检查?也许用反射或其他一些黑暗魔法?

标签: phptypescallable

解决方案


您可以使用ReflectionParameter::getType

$f = function(Foo $foo) {};

$reflectionFunc = new ReflectionFunction($f);
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();

echo $reflectionType1;

输出:


推荐阅读