Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP bitwise enums

Tags:

php

enums

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.

like image 835
Zsub Avatar asked Dec 27 '22 05:12

Zsub


1 Answers

PHP versions earlier than 5.6

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 Constants­Docs:

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

PHP 5.6 and later

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.

  • New features for PHP 5.6
like image 98
Michael Berkowski Avatar answered Jan 07 '23 20:01

Michael Berkowski