这个问题在这里已经有了答案:
PHP Constants Containing Arrays?
(17 个回答)
4年前关闭。
我正在尝试使用关联数组为每个国家/地区的办公室名称声明一个常量。
我的声明代码如下:
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
是否可以用关联数组声明一个常量?
非常感谢!!!
最佳答案
您发布的代码不适用于 PHP 5。
Declaring constant arrays using define
是一个新功能introduced in PHP 7.0 .
Since PHP 5.6可以到 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",
];
documentation突出显示
define()
之间的差异和 const
: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.
关于php - 是否可以用关联数组声明常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44964885/