3

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.

dominiq007
  • 45
  • 2
  • 4
  • Are you expecting it to run the line beginning with `#` – Nigel Ren Oct 30 '21 at 14:08
  • 1
    @NigelRen In case you're not aware, `#[...]` 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 the `MyAttribute` class constructor. The question is a reasonable one, and Kazz's answer explains the missing piece. – IMSoP Nov 02 '21 at 16:03

1 Answers1

3

Attributes can be accessed only through reflection, here is example:

// you have to specify that your custom class can serve as attribute
// by adding the build-in attribute Attribute:

#[Attribute] 
class MyAttribute {
    public function __construct($message) {
        // I want to show this message when using MyAttribute
        echo $message;
    }
}

#[MyAttribute('hello')]
class SomeClass {
    // ...
}

// first you need to create Reflection* in order to access attributes, in this case its class
$reflection = new ReflectionClass(SomeClass::class);
// then you can access the attributes
$attributes = $reflection->getAttributes();
// notice that its an array, as you can have multiple attributes
// now you can create the instance
$myAttributeInstance = $attributes[0]->newInstance();

Some documentation: ReflectionClass ReflectionAttribute

There are other Reflection* classes like: method, function, parameter, property, class constant.

Kazz
  • 1,030
  • 8
  • 16