0

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?

Pejman
  • 2,442
  • 4
  • 34
  • 62

1 Answers1

0

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
Alberto Fecchi
  • 1,705
  • 12
  • 27