その機能が本当にひどく必要な場合は、すべての定数とその値を見つけるリフレクションを使用して小さなコードを書くことができます。次に、これらをこのように変数内に設定します$CONSTANTS['CONSTANT_NAME']...
。これは、文字列に定数を入れたい場合は、{}を使用できることを意味します。また、それらをに追加するのではなく、$CONSTANTS
arrayaccessを実装するクラスにして、その中の値を変更できないようにします(配列としてアクセスできるオブジェクトに追加された新しい要素のみ)。
したがって、それを使用すると、次のようになります。
$CONSTANTS = new constant_collection();
//this bit would normally be automatically populate using reflection to find all the constants... but just for demo purposes, here is what would and wouldn't be allowed.
$CONSTANTS['PI'] = 3.14;
$CONSTANTS['PI'] = 4.34; //triggers an error
unset($CONSTANTS['PI']); //triggers an error
foreach ($CONSTANTS as $name=>$value) {
.... only if the correct interface methods are implemented to allow this
}
print count($CONSTANTS); //only if the countable interface is implemented to allow this
print "PI is {$CONSTANTS['PI']}"; //works fine :D
入力する余分な文字が数文字しかないようにするには、 ;)$C
の代わりに使用できます。$CONSTANTS
お役に立てば幸い、スコット