是否可以用关联数组声明常量 [英] Is It Possible to Declare Constant with Associative Array

查看:122
本文介绍了是否可以用关联数组声明常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 7.0中引入的新功能.

从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 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.

这篇关于是否可以用关联数组声明常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆