How can I get all the classes that have a certain attribute in php 8?

147 Views Asked by At

I have several classes with a certain attribute, how can I get all the classes that have it?

#[Attribute]
class MyAttribute {}

#[MyAttribute]
class Foo
{
}

#[MyAttribute]
class Bar
{
}

Have some ideas?

1

There are 1 best solutions below

0
LF-DevJourney On

You can make with php Reflection, or just by a bash command grep '\#\[YourAttributeName\]' -A1 -r projectfolder | grep Class | awk '{print $2}'


Here is the php way.

First use the get_declared_classes() to get all declared class. Then you can make the ReflectionClass on each class. Then check if the ReflectionClass has the attribute.

$allClasses = get_declared_classes();

foreach ($allClasses as $className) {
    $reflectionClass = new ReflectionClass($className);
    $attributes = $reflectionClass->getAttributes();

    foreach ($attributes as $attribute) {
        if ($attribute->getName() === $attributeName) {
            $classesWithAttribute[] = $className;
            break;
        }
    }
}