How to use constants with complex (curly) syntax?

I was surprised to see that the following is not working properly.

define('CONST_TEST','Some string'); echo "What is the value of {CONST_TEST} going to be?"; 

: what will be the value of {CONST_TEST}?

Is there a way to resolve constants in braces?

Yes, I know that I could just do

 echo "What is the value of ".CONST_TEST." going to be?"; 

but I would prefer not to concatenate strings, not so much for performance as for readability.

+4
source share
4 answers

Impossible because php will consider CONST_TEST as a simple string inside single / double quotes. You will need concatenation for this.

 echo "What is the value of ".CONST_TEST." going to be?"; 
+4
source

I don’t understand why you should make a big noise out of it, but you can always:

 define('CONST_TEST','Some string'); $def=CONST_TEST; echo "What is the value of $def going to be?"; 
+2
source

If you need this function very badly, you can write a little code using relfection, which will find all the constants and their values. It then sets them inside a variable of type $ CONSTANTS ['CONSTANT_NAME'] ... then that would mean if you wanted to put a constant in a string that you can use {}. Also, instead of adding them to $ CONSTANTS, make it a class that implements arrayaccess, so that you can ensure that the values ​​in it cannot be changed in any way (only new elements are added to the object to which you can get access as an array).

So using this would look like this:

 $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 that you only have a few extra characters, you could just use $ C instead of $ CONSTANTS;)

Hope this helps, Scott

+1
source

This may not be possible, but since your goal is readability, you can use sprintf / printf to achieve greater readability than string concatenation.

 define('CONST_TEST','Some string'); printf("What is the value of %s going to be?", CONST_TEST); 
0
source

All Articles