I'm trying to learn how attributes in PHP work. But when I wrote some code (I have XAMPP with PHP 8 support installed), it doesn't seem to work (no message on the screen). Does it need additonal configuration to work?
use Attribute;
class MyAttribute {
public function __construct($message) {
// I want to show this message when using MyAttribute
echo $message;
}
}
#[MyAttribute('hello')]
class SomeClass {
// ...
}
Shouldn't this code show me "hello" message? Or I don't understand something? It doesn't show anything.
##[...]is the syntax introduced in PHP 8.0 for attributes AKA annotations. It's highlighted as a comment here, and will be treated as one by earlier versions of PHP (which is one of the reasons that syntax was eventually chosen), but it is indeed a reference to theMyAttributeclass constructor. The question is a reasonable one, and Kazz's answer explains the missing piece.