Search code examples
phpphp-8php-attributes

PHP 8 Attribute constructor calling


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.


Solution

  • 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.