Home  >  Q&A  >  body text

PHP using ENUM in properties

<p>Look at the following code: </p> <pre class="brush:php;toolbar:false;"><?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 { } </pre> <p>Error <code>Constant expression contains invalid operation</code>. I want to use enum values ​​in my properties to define the configuration. Looks like this is a bug in php. Should it be reported or what? </p>
P粉593118425P粉593118425442 days ago501

reply all(1)I'll reply

  • P粉536532781

    P粉5365327812023-08-27 12:10:24

    The problem is that when we call Types::A->value, it actually creates an instance of the 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 {
    
    }
    

    Pay attention to this problem in php

    reply
    0
  • Cancelreply