phpphp-attributes

PHP attribute get target


Let's say I have the following classes:


class Bar{
    public int $id;
}

class Boo{
    public string $name;
}


class Foo{

    #[ObjectAttr]
    public Bar $barObject;

    #[ObjectAttr]
    public Boo $booObject;

}

#[\Attribute]
class ObjectAttr{
    __construct(){
        // I need to get the type of property which I used `ObjectAttr` annotation on like:
        // $className = $this->annotatedTarget()->getClassName() or something like this which returns `Bar::class` or `Boo::class`
    }
}

I need to get type of the field I used my annotation on.

Is there any convenient way to do this?


Solution

  • This seems to be a possible solution (workaround) to "inject" the property type inside an attribute using Reflection. Maybe it could satisfy your needs:

    // ...
    
    #[\Attribute]
    class ObjectAttr {
        // ...
        function test(string $name) {
            echo 'Property type: ' . $name . PHP_EOL;
            // Here you can apply your own logic
        }
    }
    
    // ...
    
    $ref = new ReflectionClass(Foo::class);
    $properties = $ref->getProperties();
    foreach($properties as $property) {
        $attributes = $property->getAttributes();
        foreach($attributes as $attribute) {
            $attribute->newInstance()->test($property->getType());
        }
    }
    

    Printed result:

    Property type: Bar
    Property type: Boo