0

I would like to call some functions in my PHP 8 attributes use cases, to clean my classes.

But I don't know how to do it and I don't find any documentation about that. This is a sample example of what I would like to do :

Imagine, we have this :

#[Assert\GreaterThanOrEqual(propertyPath: 'beginDate', message: 'No sorry, impossible')]
    private ?DateTimeInterface $endDate = null;

And I would like to get the 'message' value from a function, or an another class. So, by example :

#[Assert\GreaterThanOrEqual(propertyPath: 'beginDate', message: $this->myMessage())]
    private ?DateTimeInterface $endDate = null;

    private function myMessage(): string
    {
        return 'No sorry, impossible';
    }

I'll have an error : Constant expression contains invalid operations

Is it really possible to do this ?

eronn
  • 1,690
  • 3
  • 21
  • 53
  • You can create messages file. And then get whatever message from there. Won't that work ? – Shalini Singh Aug 31 '22 at 09:33
  • Mmmh sorry I don't understand what you mean. Note that the code above is only a simple example. Later, I would like to use the same principle but to return a large array containing a lot of information – eronn Aug 31 '22 at 09:36
  • I think the issue is explained in https://stackoverflow.com/a/40171696/1213708. As this is made into a constant, this must be defined at compile time and not runtime. – Nigel Ren Aug 31 '22 at 09:39
  • So by putting the message in a constant rather than a function, it works, yes. But there would be no way to be able to use a function? – eronn Aug 31 '22 at 09:43
  • AFAIK you would have to put this logic in the set method for this value. Not sure what you gain using attributes other than splitting the logic between the setter and the definition. – Nigel Ren Aug 31 '22 at 09:48

0 Answers0