PHP bitwise enumeration

I am trying to do something like bitwise enumeration in PHP according to this answer . However, although it worked well when I defined all constants as regular ints, for example:

final class CountryEnum { const CZ = 1; //Czech Republic const DE = 2; //Germany const DK = 4; //Denmark //12 more const US = 32768; //USA } 

This does not work when I try to determine the values ​​using the bit change 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 gives a suitable word

Parse error: parse error, pending ','' or '; ' 'in CountryEnum.php in line [line with constant DE]

So I probably missed some fundamental basic things, but I'm at a loss.

+4
source share
2 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 will always return the same value (for example, 1 << 2 ). This is because class constants are defined at compile time, and not at run time. See Class Constants & shy; Docs :

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

PHP 5.6 and later

Starting with PHP 5.6, released in 2014, constant scalar expressions are now syntactically valid and will be parsed.

You can now provide a scalar expression that includes numeric and string literals and / or constants in contexts where PHP used to expect a static value, such as constant and property declarations and default function arguments.

+7
source

You simply cannot assign a const expression in PHP (or any other property, for that matter) for some strange reason. You will have to leave them as they were before.

+3
source

Source: https://habr.com/ru/post/1398700/


All Articles