参考地址查看php的反射,链接为:https://www.php.net/manual/zh/reflectionparameter.getclass.php ,之前使用了ThinkPHP5.1的框架,发现了在函数或者类的方法里面传递类为某个参数的规定数据结构,框架能自行判断那个参数必须传入哪个类,后面我上网找了挺久才发现是php的反射功能。
如下测试代码
<?php
namespace test;
require_once dirname(__FILE__) . '/public_functions.php';
class A{
function b(B $c, array $d, $e){
}
function abc(B $b, array $ddd, $argument3){
}
}
class B{
}
class C
{
public function test(A $a, B $b){
}
}
//反射A类
$refl = new \ReflectionClass(A::class);
//获取A类里面的方法 abc 里面的参数
$par = $refl->getMethod('abc')->getParameters();
//A类里面abc方法的第一个参数类型提示
my_dump($par[0]->getClass()->getName()); // outputs B
my_dump($par[1]->getClass()); // note that array type outputs NULL
my_dump($par[2]->getClass()); // outputs NULL
function fn1(C $argument1, array $argument2, A $argument3, B $argument4, $argument5 = ''){
}
$functionReflection = new \ReflectionFunction('test\fn1');
foreach ($functionReflection->getParameters() as $index => $item) {
if ($item->isArray()) {
my_dump('参数类型是数组:array | ' . $item->__toString());
} elseif ($item->getClass()) {
my_dump('参数类型是类:' . $item->getClass()->name . ' | ' . $item->__toString());
} else {
my_dump($item->__toString());
}
}