0

I've done a lot of Googling and may have missed this, there's so many examples of using the new Attribute feature in PHP but none of them show if this is possible. What I would like to be able to do is use the current value of the class property in the constructor arguments for the attribute. Basically something like

<?php

#[\Attribute]
class MyAttr {
    public function __construct ($propValue, $otherArg) { }
}

class Test {
    #[MyAttr(__PROPERTY__, 'other')]
    public string $prop = 'MyProp';
}

So that when using ReflectionAttribute::newInstance from within the class it effectively does new Attr('MyProp', 'other'). Obviously __PROPERTY__ is wrong here, that just gives me the property name rather than its current value. Is it possible to get the property value in that context?

2
  • 2
    Attributes are supposed to carry/provide meta data. It kind of sounds like a bad design if the attribute class that's supposed to describe the property needs to know its value. But if you insist of passing value to attribute class maybe move the logic from constructor to some regular method and call it after creating new instance? That way you will be able to pass current value to the method. Commented Jul 24 at 20:34
  • Do you get this ReflectionAttribute from a ReflectionProperty? Then you are able to get the value. Commented Jul 25 at 4:17

1 Answer 1

0

No, you cannot use the property's runtime value inside the attribute constructor directly in PHP. Attributes in PHP are evaluated at parse-time, not at runtime, and they do not have access to the value of the property they annotate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.