是否可以用关联数组声明常量 [英] Is It Possible to Declare Constant with Associative Array
问题描述
我正在尝试使用关联数组为每个国家/地区的办公室名称声明一个常量.
I am trying to declare a constant for our office names of each country with associative array.
我的声明代码如下:
define( "OUR_OFFICE", [
"Japan" => "Tokyo Shibuya Office",
"Taiwan" => "Taipei Shilin Office",
"Korea" => "Seoul Yongsan Office",
"Singapore" => "Singapore Novena Office",
"Australia" => "Sydney Darlinghurst Office"
]);
但是,它仅显示消息:
警告:常数只能计算为标量值
Warning: Constants may only evaluate to scalar values
是否可以使用关联数组声明常量?
Is it possible to declare a constant with associative array?
非常感谢您!
推荐答案
您发布的代码在PHP 5上不起作用.
The code you posted doesn't work on PHP 5.
使用
从PHP 5.6起,可以
Since PHP 5.6 it is possible to define a constant array using the const
keyword:
const OUR_OFFICE = [
"Japan" => "Tokyo Shibuya Office",
"Taiwan" => "Taipei Shilin Office",
"Korea" => "Seoul Yongsan Office",
"Singapore" => "Singapore Novena Office",
"Australia" => "Sydney Darlinghurst Office",
];
The documentation highlights the differences between define()
and const
:
与使用
define()
定义常量相反,使用const
关键字定义的常量必须在顶级范围内声明,因为它们是在编译时定义的.这意味着它们不能在函数,循环,if语句或try
/catch
块中声明.
As opposed to defining constants using
define()
, constants defined using theconst
keyword must be declared at the top-level scope because they are defined at compile-time. This means that they cannot be declared inside functions, loops, if statements ortry
/catch
blocks.
这篇关于是否可以用关联数组声明常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!