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

标签 php arrays constants associative-array

这个问题在这里已经有了答案:





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 the const 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 or try/catch blocks.

关于php - 是否可以用关联数组声明常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44964885/

相关文章:

不同环境下的 PHP session 问题

Ruby:选择一组数组索引,其元素通过测试

java - Java for-each 循环中的迭代

c++ - 用 const 限定符更改替换方法 (C++)

php - GROUP BY 与事件记录?

php - 如何从access数据库导出mysql?

php - 如何将计算字段插入数据库?

javascript - 数组过滤元素彼此的值太接近

c++ - 在 C++ 中,我希望我的接口(interface) .h 说 int GetSomeInt() const;.... 但实际上方法 *DOES* 更新 "this"。

c++ - 对需要 const 引用的函数的整数输入