搜索

首页  >  问答  >  正文

PHP 在属性中使用 ENUM

<p>看下面的代码:</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>有错误 <code>常量表达式包含无效操作</code>。我想在我的属性中使用枚举值来定义配置。看起来这是 php 中的错误。应该报告还是什么?</p>
P粉593118425P粉593118425598 天前591

全部回复(1)我来回复

  • P粉536532781

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

    问题是,当我们调用 Types::A->value 时,它​​实际上创建了一个枚举的实例,它不是一个常量值。 为了解决这个问题,定义一个常量并引用它。

    <?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 {
    
    }
    

    注意这个php 中的问题

    回复
    0
  • 取消回复