PHP 按位枚举

标签 php enums

我正在尝试根据 this answer 在 PHP 中执行类似按位枚举的操作.然而,虽然当我将所有常量定义为像这样的常规整数时它工作得很好:

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

当我尝试通过移位模式定义值时它不起作用,即:

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
}

当我尝试运行它时,PHP 发出了一个合适的提示

Parse error: parse error, expecting ','' or';'' in CountryEnum.php on line [the line with const DE]

所以我可能遗漏了一些基本的基本东西,但我不知所措。

最佳答案

PHP 5.6 之前的版本

您不能在 PHP 中通过表达式定义类常量或类属性,即使表达式的结果总是返回相同的值(如 1 << 2)。这是因为类常量是在编译时而不是运行时定义的。参见 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 及更高版本

从 2014 年发布的 PHP 5.6 开始,常量标量表达式现在在语法上是有效的并且将被解析。

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.

关于PHP 按位枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9472802/

相关文章:

php - 表单不将值传递给 PHPMailer

php - Laravel+Plupload 上传到 S3 的预检响应无效 - CORS

php - 使用 foreach 2 级数组循环进行多次插入

Grails GORM 和枚举

具有 IDE 补全功能的 Javascript 伪枚举

javascript - CORS:PHP 绕过不起作用

php - 使用 $.ajax 请求从 PHP 到 MYSQL 数据库的 jQuery 表单处理

c++ - 链接两个枚举类型成员

Angular 7,枚举和输入属性绑定(bind)

c# - 比较枚举值进行排序