You can access class, property and method attributes using the method getAttributes()
(not yet documented) respectively of the classes ReflectionClass
, ReflectionProperty
and ReflectionMethod
:
$classReflection = new ReflectionClass(Sample::class);
$classAttributes = $classReflection->getAttributes();
$methodReflection = new ReflectionMethod(Sample::class, 'myFunction');
$methodAttributes = $methodReflection->getAttributes();
$propertyReflection = new ReflectionProperty(Sample::class, 'myAttribute');
$propertyAttributes = $propertyReflection->getAttributes();
For the class it is possible to use also the ReflectionObject
.
Thus $classAttributes
, $methodAttributes
and $propertyAttributes
sane arrays of instances of ReflectionAttribute
(not yet documented either), from which it is possible to call the methods of the examples in the documentation:
$classAttributes[0]->getName();
$classAttributes[0]->getArguments();
$classAttributes[0]->newInstance();
When executing var_dump
in these methods the following is displayed:
string(14) "ClassAttribute"
array(0) {
}
object(ClassAttribute)#7 (0) {
}
This way works when the name of the properties or methods is known. When the name is unknown it is necessary to iterate the instance of ReflectionObject
or ReflectionClass
with getProperties
or getMethods
. These functions return arrays containing instances of ReflectionProperty
and ReflectionMethod
, of which the attributes can be obtained according to the above example.
$classReflection = new ReflectionClass(Sample::class);
$classMethods = $classReflection->getMethods();
foreach ($classMethods as $methodReflection) {
$methodReflection->getAttributes();
}
$classMethods = $classReflection->getProperties();
foreach ($classProperties as $propertyReflection) {
$propertyReflection->getAttributes();
}