如果您非常想要该功能,您可以使用反射编写一些代码来查找所有常量及其值。然后将它们设置在像$CONSTANTS['CONSTANT_NAME']...
这样的变量中,这意味着如果您想在字符串中放入一个常量,您可以使用 {}。此外,与其将它们添加到 中$CONSTANTS
,不如将其设为实现数组访问的类,这样您就可以强制其中的值不能以任何方式更改(只有添加到对象中的新元素才能作为数组访问)。
所以使用它看起来像:
$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
;)
希望有帮助,斯科特