如何在PHP函数内获取自身属性并提取属性短名称?
PHP反射属性问题解决方案
1. 函数内部动态获取自身属性
不用硬编码方法名,借助PHP魔术常量__FUNCTION__(仅当前函数名)或__METHOD__(含类名的完整方法名)动态构建反射实例,代码更健壮,方法名修改时无需同步调整反射代码:
#[filters(['email', 'emailVerified', 'enabled', 'firstName', 'lastName', 'q', 'username'])] public function getUsers(?array $filter = null): iterable { // 动态获取当前方法的反射实例 $method = new \ReflectionMethod($this, __FUNCTION__); // 也可以用 ReflectionClass 方式实现 // $method = (new \ReflectionClass($this))->getMethod(__FUNCTION__); // 直接获取指定的filters属性:若文件顶部已use Base\Service\Client\filters;,可直接传'filters' $attributes = $method->getAttributes(\Base\Service\Client\filters::class); $f = []; foreach ($attributes as $reflection) { $f[$reflection->getName()] = $reflection->getArguments(); } dd($f); }
2. 提取属性短名称(去除命名空间)
原生PHP字符串处理
通过截取最后一个反斜杠后的内容得到短名称:
foreach ($attributes as $reflection) { $fullName = $reflection->getName(); $shortName = substr($fullName, strrpos($fullName, '\\') + 1); $f[$shortName] = $reflection->getArguments(); }
反射类方式(更可靠)
通过属性类的反射实例直接获取短名称,避免字符串处理的潜在问题:
foreach ($attributes as $reflection) { $attrReflection = new \ReflectionClass($reflection->getName()); $shortName = $attrReflection->getShortName(); $f[$shortName] = $reflection->getArguments(); }
框架辅助函数(如Laravel)
如果是Laravel项目,可直接用框架内置的class_basename函数:
$shortName = class_basename($reflection->getName());
修改后最终输出会变为:
[ 'filters' => [ (int) 0 => [ (int) 0 => 'email', (int) 1 => 'emailVerified', (int) 2 => 'enabled', (int) 3 => 'firstName', (int) 4 => 'lastName', (int) 5 => 'q', (int) 6 => 'username', ], ], ]
内容的提问来源于stack exchange,提问作者M.btm
相关产品推荐
相关产品推荐

