php - 检查可调用是否可以接收类作为php中的参数
问题描述
我有一个可调用对象$f
,我想知道它是否可以接收某个类的实例Foo
作为输入。
目前我正在做类似的事情
try {
$f($foo);
} catch (\TypeError $e) {
throw new \InvalidArgumentException('The provided function can not evaluate inputs of this type');
}
有没有办法在不实际调用可调用对象的情况下进行检查?也许用反射或其他一些黑暗魔法?
解决方案
您可以使用ReflectionParameter::getType:
$f = function(Foo $foo) {};
$reflectionFunc = new ReflectionFunction($f);
$reflectionParams = $reflectionFunc->getParameters();
$reflectionType1 = $reflectionParams[0]->getType();
echo $reflectionType1;
输出:
富
推荐阅读
- debugging - VS2017 条件断点 - “不支持在此上下文中评估本机方法”
- laravel - 求和多维数组
- python - Tensorflow - 除非我重新创建“保护程序”对象,否则无法初始化保存的变量。为什么?
- firebase - 无法在 ios 中接收通知:发送 FcmTokenRefreshed 且未注册监听器
- python - 创建一个最小的烧瓶/请求文件上传器
- javascript - 如何在 curl 中编写 PUT 请求并访问 Node.js 中的参数?
- android - 错误:错误:包 SpotsDialog 不存在
- python - 绘制具有数百万行的列
- c++ - What is the cheapest way to sort a permutation in C++?
- javascript - how to prevent multiple decimals in javascript calculator