简体   繁体   中英

What is the most “elegant” way to define a global constant array in PHP

I was wondering what do you think would be the best and cleanest way to define a constant array variable similar to the way define function works. I've seen a lot of people asking this question in Google and so far the easiest solution I have come up with is to use the PHP serialize function inside the define statement, like this

define ("MY_ARRAY", serialize (array ("key1" => $value1,"key2" => $value2, ..)));

then to use the defined constant you can do something like this:

$MY_ARRAY = unserialize (MY_ARRAY)
print_r ($MY_ARRAY);

Not sure if the serialize function will slow you down if you have a lot of defines in your code. What do you think?

$GLOBALS['MY_ARRAY'] = array();

The serialization and especially unserialization is pretty awkward. (On the other hand it's not quite clear why a scripting language can't have arrays as constants...)

But it really depends on the usage pattern. Normally you want global defines for storing configuration settings. And global variables and constant are an appropriate use for that (despite the "globals are evil!!1!" meme). But it's advisable to throw everything into some sort of registry object or array at least:

class config {
     var $MY_ARRAY = array("key1"=>...);
     var $data_dir = "/tmp/";
} 

This gives the simplest access syntax with config::$MY_ARRAY . That's not quite an constant, but you can easily fake it. Just use an ArrayObject or ArrayAccess and implement it in a way to make the attributes read-only. (Make offsetSet throw an error.)

If you want a global array constant workaround, then another alternative (I've stolen this idea from the define manual page ) is to use a function in lieu of a constant:

function MY_ARRAY() {
     return array("key1" => $value1,);
}

The access is again not quite constantish, but MY_ARRAY() is short enough. Though the nice array access with MY_ARRAY()["key1"] is not possible prior PHP 5.3; but again this could be faked with MY_ARRAY("key1") for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM