在 PHP 8 中使用反射 API 读取属性
phpserver side programmingprogramming更新于 2025/8/29 3:52:17
在 PHP 8 中,我们使用类、属性、类常量、方法、函数和参数来访问属性。
在 PHP 8 中,反射 API 为每个匹配的反射对象提供 getAttribute() 方法。
getAttribute() 方法返回一个 ReflectionAttribute 实例数组,可以向该数组中传入属性名称、参数,并实例化指定属性的实例。
示例 − 在 PHP 8 中使用反射 API 读取属性
<?php
#[Reading]
#[Property(type: 'function', name: 'Student')]
function Student()
{
return "Student";
}
function getAttributes(Reflector $reflection)
{
$attributes = $reflection->getAttributes();
$finalresult = [];
foreach ($attributes as $attribute)
{
$finalresult[$attribute->getName() ] = $attribute->getArguments();
}
return $finalresult;
}
$reflection = new ReflectionFunction("Student");
print_r(getAttributes($reflection));
?>
输出
Array ( [Reading] => Array ( ) [Property] => Array ( [type] => function [name] => Student ) )

