It doesn't introduce much overhead if you make use of conditional function definitions:
<?php
if (function_exists('apc_load_constants')) {
function define_array($key, $arr, $case_sensitive = true)
{
if (!apc_load_constants($key, $case_sensitive)) {
apc_define_constants($key, $arr, $case_sensitive);
}
}
} else {
function define_array($key, $arr, $case_sensitive = true)
{
foreach ($arr as $name => $value)
define($name, $value, $case_sensitive);
}
}
//in your code you just write something like this:
define_array('NUMBERS', Array('ONE' => 1, 'TWO' => 2, 'THREE' => 3));
?>
apc_define_constants
(PECL apc >= 3.0.0)
apc_define_constants — 定数の組を定義し、それを取得あるいは一括定義する
説明
ご存知のとおり、define() は非常に遅いです。 APC を使用する主な利点はスクリプト/アプリケーションのパフォーマンスの改善なので、 大量の定数を定義する手順を合理化するために、この仕組みが提供されています。 しかし、この関数は期待通りの動作をしません。
よりよい解決策として、PECL の » hidef 拡張モジュールを試してみましょう。
注意: (キャッシュ全体をクリアすることなく)格納されている定数を削除するには、 constants に空の配列を渡します。そうすれば、 そこに格納されていた値は事実上削除されます。
パラメータ
- key
-
key は、格納される定数群の名前を表します。 この key は、格納されている定数を apc_load_constants() で取得するために使用されます。
- constants
-
constant_name => value 形式の連想配列。 constant_name は、一般の 定数 の命名規則に従う 必要があります。 value は、スカラ値でなければ なりません。
- case_sensitive
-
デフォルトでは、定数名の大文字・小文字は区別されます。すなわち、 CONSTANT と Constant は別の値を表します。このパラメータを FALSE にすると、 定数名の大文字・小文字は区別されなくなります。
返り値
成功した場合に TRUE を、失敗した場合に FALSE を返します。
例
例1 apc_define_constants() の例
<?php
$constants = array(
'ONE' => 1,
'TWO' => 2,
'THREE' => 3,
);
apc_define_constants('numbers', $constants);
echo ONE, TWO, THREE;
?>
上の例の出力は以下となります。
123
参考
- apc_load_constants() - 定数群をキャッシュから読み込む
- define() - 名前を指定して定数を定義する
- constant() - 定数の値を返す
- あるいは PHP リファレンスの「定数」
An observation that I've made is that the nature of apc_define_constants() binding the list of constants to a key and then requiring that key to load the constants is limiting. Furthermore, there's no way to append additional constants to a given key.
A solution that I've been adopting is to build a list of constants to be defined, and then do one of two things:
1) if APC is enabled, then use apc_define_constants();
2) ...else loop through the list and define each constant normally.
The problem I've run into is when this process happens at different places in a large application, it can introduce overhead that otherwise wouldn't be there if it was possible to append to an existing list of defined constants in APC.
