ReflectionClass 通过 getMethods() 获取所有方法,传 ReflectionMethod::IS_PUBLIC 等标志可筛选可见性或 static 方法;getMethod($name) 精准获取单个方法实例,区分大小写且抛出 ReflectionException;getParameters() 和 getReturnType() 用于获取参数与返回类型信息,但 PHP 7.2 不支持联合类型和 void 类型反射。

ReflectionClass 怎么获取类的所有方法
直接用 getMethods() 就能拿到一个 ReflectionMethod 数组,但默认返回所有可见性(public、protected、private)的方法。如果只想看 public 方法,得传参数:ReflectionMethod::IS_PUBLIC。
-
getMethods()不加参数 → 返回全部方法(含 private/protected) -
getMethods(ReflectionMethod::IS_PUBLIC)→ 只返回 public 方法 - 想查 static 方法?用
ReflectionMethod::IS_STATIC组合:比如getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_STATIC) - 注意:
getMethods()不会递归获取父类方法,只查当前类定义的;要包含继承来的,得手动遍历父类链
怎样获取某个特定方法的 ReflectionMethod 实例
用 getMethod($name),传方法名字符串。它比 getMethods() 更精准,也更快——尤其当你只关心一个方法时。
- 如果方法不存在,抛出
ReflectionException,不是返回 false 或 null,记得 try/catch - 方法名区分大小写:
getMethod('Foo')和getMethod('foo')是不同调用 - 静态方法、构造函数(
__construct)、析构函数(__destruct)都能通过这个名字获取 - 如果目标是检查方法是否存在且可调用,不如先用
method_exists($class, $name)快速判断,再决定是否反射
获取方法签名和参数信息的实际用法
拿到 ReflectionMethod 对象后,常用的是 getParameters() 和 getReturnType()(PHP 7.2 支持返回类型反射,但不支持 void 类型的 getReturnType() 返回 null)。
-
getParameters()返回ReflectionParameter数组,每个能调用getName()、getType()(返回ReflectionNamedType或null)、isOptional() - PHP 7.2 中
getType()对联合类型(如string|int)不支持,只识别单类型声明;没声明类型时返回null -
getReturnType()在无返回类型声明时也返回null;若声明了self或parent,返回的是ReflectionNamedType,但其getName()是字符串"self",不是类名 - 别依赖
getDocComment()解析 PHPDoc 类型,PHP 7.2 的反射不解析注释,那是第三方库(如 phpdocumentor/type-resolver)的事
常见报错和兼容性注意点
PHP 7.2 的 ReflectionClass 行为和后续版本有细微差异,尤其在类型反射和魔术方法处理上。
立即学习“PHP免费学习笔记(深入)”;
-
ReflectionException: Class xxx does not exist:说明传给new ReflectionClass()的类名没 autoload 进来,或拼写错误;先确认class_exists($class)返回 true -
ReflectionException: Method xxx::yyy() does not exist:方法名错、大小写不对、或方法是动态生成的(如 __call),反射拿不到 - 匿名类不能被
ReflectionClass构造:传入匿名类实例的get_class($obj)得到的是类似"class@anonymous/path/to/file.php0x12345678"的名字,直接 new ReflectionClass 会失败 - PHP 7.2 不支持
getAttributes()(PHP 8+ 才有),别在代码里误用
反射开销不小,别在高频循环里反复 new ReflectionClass;真需要多次查同一个类,缓存实例更稳妥。



















