About the PHP constants

March 7th, 2005. Tagged: PHP certification

The reader of the PHP cert guide might be wondering about some aspects of the PHP constants, because the constants section of the book doesn't go into as much detail as it goes for other sections like variables for example.

1. It's not necassary to name the constants always in upper case. It is, however, a good practice, kind of an unspoken convension. You'll make your code easier to read (and maintain) if you always use upper case.

2. You don't have to use double quotes when defining a constant. In fact, when you don't have a reason to use double quotes, always use single quotes, it's better in terms of performance.

En example to illustrate the two points above:
< ?php define ('something', 123); echo something; ?>

3. Constants names are case-sensitive. So the following will not work as expected:
< ?php define ('something', 123); echo someThing; ?>

4. You cannot include a constant's value as part of a string as you can do with a variable. Here's an illustration:
< ?php $var = 'test'; define ('CONST', 123); echo "testing $var variable"; echo "testing {$var} variable"; echo "testing SOMETHING constant"; echo "testing {SOMETHING} constant"; ?>
This will result in:
testing test variable
testing test variable
testing SOMETHING constant
testing {SOMETHING} constant

Tell your friends about this post on Facebook and Twitter

Sorry, comments disabled and hidden due to excessive spam.

Meanwhile, hit me up on twitter @stoyanstefanov