PHP using ENUM in properties
P粉593118425
P粉593118425 2023-08-26 23:17:00
0
1
499
<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粉593118425
P粉593118425

reply all(1)
P粉536532781

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!