首頁  >  問答  >  主體

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粉593118425392 天前451

全部回覆(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
  • 取消回覆