phpenumsphp-8.1php-attributes

PHP use ENUM in Attributes


Look at the following code:

<?php

enum Types:string {
    case A = 'a';
    case B = 'b';
}

#[Attribute(Attribute::TARGET_CLASS)]
class MyAttribute {
    public function __construct(public readonly array $mapping)
    {
    }
}

#[MyAttribute(mapping: [Types::A->value => ''])]
class Entity {

}

It has error Constant expression contains invalid operations. I would like to use Enum value in my attribute for defining configuration. Seem like it is bug in php. Should it be reported or something?


Solution

  • The problem is that when we call Types::A->value it actually creates instance of an enum, which is not a constant value. To solve this problem define a constant and reference it.

    <?php
    
    abstract class Type {
        public const A = 'a';
        public const B = 'b';
    }
    
    enum TypesEnum:string {
        case A = Type::A;
        case B = Type::B;
    }
    
    #[Attribute(Attribute::TARGET_CLASS)]
    class MyAttribute {
        public function __construct(public readonly array $mapping)
        {
        }
    }
    
    #[MyAttribute(mapping: [Type::A => ''])]
    class Entity {
    
    }
    

    Watch out for this issue in php