4

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.

2
  • Are you expecting it to run the line beginning with # Commented Oct 30, 2021 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. Commented Nov 2, 2021 at 16:03

1 Answer 1

4

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.

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.