How to use constants with Complex (curly) syntax?
I was surprised to see that the following doesn't work as expected.
define('CONST_TEST','Some string');
echo "What is the value of {CONST_TEST} going to be?";
outputs:开发者_Go百科 What is the value of {CONST_TEST} going to be?
Is there a way to resolve constants within curly braces?
Yes, I am aware I could just do
echo "What is the value of ".CONST_TEST." going to be?";
but I'd prefer not to concatanate strings, not so much for performance but for readability.
Nope that's not possible because php will consider CONST_TEST
to be a mere string inside the single/double quotes. You will have to use the concatenation for that.
echo "What is the value of ".CONST_TEST." going to be?";
i don't understand why you have to make a big fuss out of it but you can always do:
define('CONST_TEST','Some string');
$def=CONST_TEST;
echo "What is the value of $def going to be?";
It may not be possible, but since your goal is readability, you could use sprintf/printf to achieve better readability than through string concatenation.
define('CONST_TEST','Some string');
printf("What is the value of %s going to be?", CONST_TEST);
If you wanted that feature really badly, you could write a little code using reflection that finds all the constants and their values. Then sets them inside a variable like $CONSTANTS['CONSTANT_NAME']...
this would then mean if ever you want to put a constant in a string you can using {}. Also, rather than add them to $CONSTANTS
, make it a class that implements arrayaccess so you can enforce that the values in it can not be changed in any way (only new elements added to the object which can be accessed as an array).
So using it would look like:
$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
To make it so you only have a few extra characters to type you could just use $C
instead of $CONSTANTS
;)
Hope that helps, Scott
精彩评论