Skip Navigation
Madison, Wisconsin
Powderkeg Web Design
March 30, 2015

PHP, Constants, and You

Matt
Matt
PHP, Constants, and You

An often underused aspect of PHP is the use of constant variable.

As defined by the PHP docs:

A constant is an identifier (name) for a simple value. As the name suggests, that value cannot change during the execution of the script (except for magic constants, which aren’t actually constants). A constant is case-sensitive by default. By convention, constant identifiers are always uppercase. The name of a constant follows the same rules as any label in PHP. A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thusly: [a-zA-Z_x7f-xff][a-zA-Z0-9_x7f-xff]*

Usage

The main reason for using constants is defining something you do not want to be overridden in the global namespace. Constants are called via name only instead of with the dollar sign like a regular variable.

// "regular" variables
$my_var = 'Hello, World!';
echo $my_var;

// constant variables
define('MY_VAR', 'Hello, World!');
echo MY_VAR;

Issues

One of the main issues we recently ran into is how constants are evaluated. When trying to reference a constant that is undefined, it will not return null like a regular variable. Instead, they return the constant name as a string value.

// undefined "regular" variables
echo 'Echo '.$my_var.'<br />';
if(!$my_var) {
	echo '$my_var is undefined';
}

Output:
"Echo
$my_var is undefined"

echo 'Echo '.MY_VAR.'<br />';
if(!MY_VAR) {
	echo 'MY_VAR is undefined';
}

Output:
"Echo MY_VAR"

As you can see, constants do not conform to how regular variables are evaluated.

Solution

Instead of using the popular !$my_var shorthand, you should always use the constant() function.

if(!constant('MY_VAR')) {
	echo 'MY_VAR is undefined';
}
Matt Engelbregtsen

Matt Engelbregtsen

Technical Account Manager