Thursday, 30 August 2018

PHP - Is it possible to declare Constant with associative Array

This question already has an answer here:

  • PHP Constants Containing Arrays? 19 answers
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!!!

The code you posted doesn't work on PHP 5.
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.

0 comments:

Post a Comment