In programming, a constant is anything that is supposed to be the same all the time and cannot be changed. Basically is is that way at least until the program starts again. In PHP constants are not similar to variables in syntax, which is in some ways a surprise. I’ll quickly show you a C constant and then a PHP constant.

constants in C:
const int AARDVARK = 2;

constants in PHP:
define(‘AARDVARK’, 2);

normal variables in PHP:

So the first thing to keep in mind is that constants are defined and used a bit differently than variables in PHP.

define('MAXIMUM', 500);
if($amount > MAXIMUM){
    die("amount was greater than maximum!");

That example pretty much sums up normal constant usage. If somehow we didn’t know if the constant was set yet we could do something like this.

if(defined('MAXIMUM') == false)
    define('MAXIMUM', 9999);
if($amount > MAXIMUM){
    die("amount was greater than maximum!");

Back to the first concept, why choose to make something a constant rather than a variable. It’s often intended to be a technique to minimize bugs, even though the bugs would be caused by the programmers. It’s just safer to have a value that cannot be edited rather than one that can but will cause problems if it is. There are also reasons like clarity, separating regular variables visually from constant data. In PHP constants are also super globals, similar to $_POST for example, they can be used anywhere once defined. All the more reason that you cannot set a constant to a different value, since you have global access to it. Predefined Constants are another major part of PHP as they handle a lot of things specific to various areas of PHP without taking up variable names. For example the MySQL module in PHP has a lot of constants that are defined before your script runs.

Let’s try to answer some questions that may come up…

Why are constants always uppercase?
They are not, they can use the same characters that variables use. They are often that way because it is a convention in programming to make defined global values all uppercase so they are easily spotted, and other reasons.

Can I unset a constant?
As you know they cannot be changed, and in PHP they cannot be unset or deleted.

Can I use a string with the name of a constant to get a constant’s value?
Yes, the function constant() does that, $value = constant(‘CONSTANTNAME’);

Some constants have 2 underscores in front and 2 behind, what do they do?
Some are normal constants and it’s just a way to name them. Some are Magic Constants.

Magic constants?
You can find a list of them in the PHP manual. They are defined automatically, and often change by themselves depending on what file the script is in, what line it is on, or what function it is used in. They aren’t much like constants in that respect.