如何从PHP对象及Simple类中获取并筛选Getter方法?
如何从PHP对象/类中筛选Getter方法
这是日常PHP开发中处理数据对象时很常见的需求,尤其是在需要自动映射属性或生成表单的时候!针对你的问题,我来一步步拆解解决方案:
首先明确Getter的常规规则
通常我们说的Getter方法满足这些特征:
- 方法名以
get开头 - 紧随
get的是大写字母(符合驼峰命名,比如getTest对应私有属性$test) - 方法没有参数(Getter的作用是读取属性,不需要传入参数)
- 方法长度至少4个字符(避免
get()这种无意义的方法)
针对你的Simple类筛选Getter
你已经通过ReflectionClass拿到了所有方法,接下来只需要按照上面的规则对$allMethods进行筛选即可。先纠正你代码里的一个小笔误:给定的类是Simple,所以实例化时应该是new Simple()而不是SimpleClass()。
具体实现代码
class Simple { private $test; public function other() {}; public function getTest() {}; public function setTest() {}; public function getSecond() {}; public function setSecond() {}; } // 初始化反射类 $ref = new \ReflectionClass(new Simple()); $allMethods = $ref->getMethods(); // 筛选Getter方法 $getterMethods = array_filter($allMethods, function(\ReflectionMethod $method) { $methodName = $method->getName(); // 核心筛选条件 return str_starts_with($methodName, 'get') && strlen($methodName) > 3 && ctype_upper($methodName[3]) && $method->getNumberOfParameters() === 0; }); // 如果只需要方法名数组,可以这样转换 $getterNames = array_map(fn($method) => $method->getName(), $getterMethods); print_r($getterNames);
代码说明
str_starts_with($methodName, 'get'):判断方法是否以get开头(PHP 8.0+支持,低版本可以用substr($methodName, 0, 3) === 'get'替代)strlen($methodName) > 3:排除get()这类无效方法ctype_upper($methodName[3]):确保get后的第一个字母是大写,符合标准Getter的驼峰命名规范$method->getNumberOfParameters() === 0:过滤掉带参数的get开头方法(比如某些特殊场景的getSomething($id)不属于常规Getter)
运行这段代码后,会输出:
Array ( [0] => getTest [1] => getSecond )
扩展说明
如果你的项目中有特殊的Getter规则(比如布尔属性用is开头,比如isActive),只需要在筛选条件里添加对应的判断即可,比如:
return (str_starts_with($methodName, 'get') || str_starts_with($methodName, 'is')) && strlen($methodName) > 3 && ctype_upper($methodName[3]) && $method->getNumberOfParameters() === 0;
内容的提问来源于stack exchange,提问作者fotic
相关产品推荐
相关产品推荐

