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