You might be familiar with using PHP variables to store values in PHP scripts. PHP constants are similar, but have a few important differences, as you’ll see in this article.
PHP constants explained
Like variables, PHP constants can store values. However, once a constant has been created, its value cannot be changed while the script runs.
Constants are useful for storing data that doesn’t (and shouldn’t) change while the script is running. Common examples of such data include configuration settings (such as database usernames and passwords) and fixed strings of text to display to visitors (such as “Please login to continue”).
Constants are also often used to represent integer values with special meanings in a particular context, such as error codes and flags.
How to create a constant
PHP constant names follow the same rules as PHP variable names. The only difference is that constant names don’t start with a
$ (dollar) symbol, while variable names do.
PHP constant names are case-sensitive. Usually, constant names use all-uppercase letters, with underscores to separate words within the name.
To create a PHP constant, use the following syntax:
define( "CONSTANT_NAME", constant_value );
“CONSTANT_NAME” is a string holding the name of the constant to create, while constant_value is the value that the constant will hold. Here are a couple of examples:
define( "HELLO", "Hello, world!" ); define( "WIDGET_PRICE", 29.99 );
The first line of code creates a PHP constant called
HELLO with a string value of “Hello, world!”, while the second line creates a constant called
WIDGET_PRICE with a numeric value of 29.99.
Using constants in PHP
You access a PHP constant in exactly the same way as you use a variable. To use a constant’s value, simply write the constant name. The following example displays the values of the
echo HELLO; echo WIDGET_PRICE;
PHP features a large number of built-in, predefined constants holding various useful values. Some of these are always available, while other constants become available when certain PHP extensions are enabled.
For example, the PHP constant
M_PI holds the mathematical constant Pi. The following code displays this value:
Another useful predefined constant is
PHP_VERSION, which holds the current version of the running PHP engine:
The PHP website has a list of built-in predefined constants.
You now know what PHP constants are, as well as how to create constants and use them. Happy coding!