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

时间秒杀一切 提交于 2019-12-09 15:25:33

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4637402/what-is-the-most-elegant-way-to-define-a-global-constant-array-in-php

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