Is It Possible to Declare Constant with Associative Array [duplicate]

我怕爱的太早我们不能终老 提交于 2019-12-08 05:44:00

问题


I am trying to declare a constant for our office names of each country with associative array.

My declaring code is as below:

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

However, it just shows message:

Warning: Constants may only evaluate to scalar values

Is it possible to declare a constant with associative array?

Thank you very much!!!


回答1:


The code you posted doesn't work on PHP 5.

Declaring constant arrays using define is a new feature introduced in PHP 7.0.

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:

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.




回答2:


In PHP 7, array values are also accepted.

But prior PHP 7, you maybe can do this, to pass an array elsewhere using define:

$array = [
    "Japan" => "Tokyo Shibuya Office",
    "Taiwan" => "Taipei Shilin Office",
    "Korea" => "Seoul Yongsan Office",
    "Singapore" => "Singapore Novena Office",
    "Australia" => "Sydney Darlinghurst Office"
];

$define_array = serialize($array);

define( "OUROFFICE", $define_array );

$our_office = unserialize(OUROFFICE);

print_r($our_office);


来源:https://stackoverflow.com/questions/44964885/is-it-possible-to-declare-constant-with-associative-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!