是否可以用关联数组声明常量

Ed *_*hen 1 php arrays associative-array constants

我正在尝试使用关联数组为每个国家/地区的办公室名称声明一个常量。

我的声明代码如下:

define( "OUR_OFFICE", [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
]);
Run Code Online (Sandbox Code Playgroud)

但是,它仅显示消息:

警告:常数只能计算为标量值

是否可以使用关联数组声明常量?

非常感谢你!!!

axi*_*iac 9

您发布的代码在PHP 5上不起作用。

使用声明常量数组definePHP 7.0中引入的新功能。

从PHP 5.6开始,可以使用const关键字定义常量数组

const OUR_OFFICE = [
    "Japan"     => "Tokyo Shibuya Office",
    "Taiwan"    => "Taipei Shilin Office",
    "Korea"     => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office",
];
Run Code Online (Sandbox Code Playgroud)

文档着重说明了define()和之间的区别const

与使用定义常量相反define(),使用const关键字定义的常量必须在顶级范围内声明,因为它们是在编译时定义的。这意味着它们不能在函数,循环,if语句或try/ catch块内声明。