php - 获取类方法参数类型
问题描述
我正在阅读有关 php 的信息ReflectionFunction
。是否可以使用它来检查类方法的各种参数的类型?
解决方案
您必须使用ReflectionMethod
该类而不是ReflectionFunction
:
class Test {
public function Test1(int $number, string $str) { }
}
//get the information about a specific method.
$rm = new ReflectionMethod('Test', 'Test1');
//get all parameter names and parameter types of the method.
foreach ($rm->getParameters() as $parameter) {
echo 'Name: '.$parameter->getName().' - Type: '.$parameter->getType()."\n";
}
演示: https ://ideone.com/uBUghi
您可以使用以下解决方案来获取所有方法的所有参数,使用ReflectionClass
:
class Test {
public function Test1(int $number, string $str) { }
public function Test2(bool $boolean) { }
public function Test3($value) { }
}
//get the information of the class.
$rf = new ReflectionClass('Test');
//run through all methods.
foreach ($rf->getMethods() as $method) {
echo $method->name."\n";
//run through all parameters of the method.
foreach ($method->getParameters() as $parameter) {
echo "\t".'Name: '.$parameter->getName().' - Type: '.$parameter->getType()."\n";
}
}
推荐阅读
- vba - Solidworks 宏按钮 - 方法下拉列表为空
- kubernetes - 使用 Prometheus Adapter 来自其他部署的 Kubernetes HPA 自定义指标
- html - 如何将子 div 放在文档的左上角。甚至高于父母的div?
- c# - 当所有骰子掷出相同的数字时,会中断 while 循环
- database - AWS Glue Databrew 上是否有办法平均最后一个有效值和下一个有效值?
- java - 允许“new int[] {0}[0] = 1;”的Java语法是什么 编译?
- java - JPF 模拟给出索引数组边界的错误
- vector - 字体标题中的魔法值错误:clisp 中的 #x0A3B3B3B(预期为 #x00010000 或 #x74727565 或 #x74746366)
- python - validate_pin 练习,不要知道我错在哪里,或者我是否是好赛道
- sql - 如何在 SQL BigQuery 中使用 CTE 显示和计算多天