Search
Close this search box.
Search
Close this search box.

Using Constants

There are many data types in PHP like numbers, strings, and arrays. Constants are another data type, but unlike variables, their values cannot change.

Whereas variables are assigned values via the assignment operator (=), constants are assigned values using the define() function:

define('CONSTANT_NAME', value);

Notice that—as a rule of thumb—constants are named using all capital letters, although doing so isn’t required. Most important, constants don’t use the initial dollar sign as variables do (because constants are not variables). Here are two constants:

define ('PI', 3.14);
define ('CURRENCY', 'euros');

As with any value, quote those that are strings, not those that are numbers.

Referring to constants is generally straightforward:

print CURRENCY;

But using constants within quotation marks is more complicated. You can’t print constants within single or double quotation marks, like this:

print "The cost is 468 CURRENCY"; // WRONG

Instead, concatenation or multiple print statements are required:

print 'The cost is 468 ' . CURRENCY; // CORRECT