php中isdefin,在PHP中定義全局常量數組的最“優雅”方法是什么
6
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:
但這實際上取決於使用模式。通常,您需要全局定義來存儲配置設置。全局變量和常量是適當的用途(盡管“全局變量是邪惡的!1!”meme)。但建議至少將所有內容都放入某種注冊表對象或數組中:
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.)
這為config :: $ MY_ARRAY提供了最簡單的訪問語法。這不是一個常數,但你很容易偽造它。只需使用ArrayObject或ArrayAccess並以一種使屬性為只讀的方式實現它。 (使offsetSet拋出錯誤。)
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.
訪問再次不是很穩定,但MY_ARRAY()足夠短。盡管PHP 5.3之前不可能使用MY_ARRAY()[“key1”]進行良好的數組訪問;但同樣可以用MY_ARRAY(“key1”)偽造一下。
總結
以上是生活随笔為你收集整理的php中isdefin,在PHP中定義全局常量數組的最“優雅”方法是什么的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 螺蛳粉怎么样 品尝螺蛳粉的口感和特点?
- 下一篇: 寄居蟹能吃汉菜吗?