What a Constant is and how to declare one

In PHP values that are stored in variables are updated all the time. What happens when you need a value to maintain consistency though? For that you can use constants. Similar to how we can assign a value to a variable, we also assign a value to a constant but the difference is that once you set that constant value, it cannot be modified. Let’s say you want to be sure the values of certain variables will not change in your application. For example it would be smart to determine that your variable named $oneminute has a value of 60 seconds. We can declare that in a constant like so:

Notice that we use the define keyword and the constant is in uppercase with no dollar sign prefix. A different application might be setting the value of a T-shirt you might want to sell on your website. Maybe you want to be sure it sells for $15 and will not be altered elsewhere by the program. Let’s create that constant now:

Now you can be confident that when you are doing calculations and updates using the TSHIRT constant, the correct value will be assigned to that constant. You can be confident that the correct value is present and will not get modified by accident.

The uppercase convention of constants comes from the C programming language. C is the foundation of all computer science and runs everything from the popular Linux operating system which often runs apache and MySQL to serve up webpages, to the operating system of cisco routers and switches, both of which power the vast majority of the internet. Having this uppercase format makes it easy to identify in the code.

You are free to define as many constants as you may need in your program. PHP has a large amount of its own pre-defined constants. To check which are in use on your particular installation, you can run the phpinfo() function in one of your pages to view a dump of all the configuration parameters including constants.

Be sure to also note that constants can only store values of type integer, float, Boolean, or string. In other words, constants are used for scalar data type storage.