【问题标题】:PHP use ENUM in AttributesPHP 在属性中使用 ENUM
【发布时间】:2022-11-18 01:55:47
【问题描述】:

看下面的代码:

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

}

它有错误Constant expression contains invalid operations。我想在我的属性中使用枚举值来定义配置。好像是 php 中的错误。是不是应该举报之类的?

【问题讨论】:

    标签: php enums php-8.1 php-attributes


    【解决方案1】:

    问题是,当我们调用 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 {
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-09
      • 2019-02-11
      相关资源
      最近更新 更多