PHP using ENUM in properties
P粉593118425
2023-08-26 23:17:00
<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>
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.
Pay attention to this problem in php