什么是最“优雅”的? PHP中定义全局常量数组的方法
我想知道您认为定义常量数组变量的最好、最干净的方法是什么,类似于 define 函数的工作方式。我在 Google 上看到很多人问这个问题,到目前为止,我想出的最简单的解决方案是在 define 语句中使用 PHP serialize 函数,像这样
define ("MY_ARRAY", serialize (array ("key1" => $value1,"key2" => $value2, ..)));
,然后要使用定义的常量,您可以执行以下操作:
$MY_ARRAY = unserialize (MY_ARRAY)
print_r ($MY_ARRAY);
如果代码中有很多定义,不确定序列化函数是否会减慢您的速度。你怎么认为?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
序列化,尤其是反序列化非常尴尬。 (另一方面,不太清楚为什么脚本语言不能将数组作为常量......)
但这实际上取决于使用模式。通常您需要全局定义来存储配置设置。全局变量和常量是一个合适的用途(尽管有“全局变量是邪恶的!!1!”模因)。但建议至少将所有内容放入某种注册表对象或数组中:
这提供了最简单的访问语法
config::$MY_ARRAY
。这并不是一个常数,但你可以很容易地伪造它。只需使用 ArrayObject 或 ArrayAccess 并以使属性只读的方式实现它即可。 (使 offsetSet 抛出错误。)如果你想要一个全局数组常量解决方法,然后是另一种选择(我从 定义手册页 窃取了这个想法) 是使用函数代替常量:
访问也不太恒定,但 MY_ARRAY() 足够短。尽管在 PHP 5.3 之前无法使用
MY_ARRAY()["key1"]
进行良好的数组访问;但同样可以使用MY_ARRAY("key1")
来伪造。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:
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:
The access is again not quite constantish, but
MY_ARRAY()
is short enough. Though the nice array access withMY_ARRAY()["key1"]
is not possible prior PHP 5.3; but again this could be faked withMY_ARRAY("key1")
for example.