I'm trying to do something like a bitwise enum in PHP according to this answer. However, while it worked nicely when I had defined all constants as regular ints like this:
final class CountryEnum {
const CZ = 1; //Czech Republic
const DE = 2; //Germany
const DK = 4; //Denmark
//12 more
const US = 32768; //USA
}
It doesn't work when I try to define the values via a bit-shift pattern, i.e.:
final class CountryEnum {
const CZ = 1; //Czech Republic
const DE = 1 << 1; //Germany
const DK = 1 << 2; //Denmark
//12 more
const US = 1 << 15; //USA
}
When I try to run this, PHP thows a fit saying
Parse error: parse error, expecting
','' or
';'' in CountryEnum.php on line [the line with const DE]
So I am probably missing some fundamental basic thingy, but I'm at a loss.
You cannot define a class constant or class property by an expression in PHP, even if the result of the expression would always return the same value (like 1 << 2
) . This is due to the fact that class constants are defined at compile time, not runtime. See Class ConstantsDocs:
The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.
As of PHP 5.6, released in 2014, constant scalar expressions are now syntactically valid and will be parsed.
It is now possible to provide a scalar expression involving numeric and string literals and/or constants in contexts where PHP previously expected a static value, such as constant and property declarations and default function arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With