Everything You Need To Know About PHP Constants

Posted by TotalDC

If you are reading this post, probably you may be new to PHP and programming in general. In that case, if you need an intro into what is PHP variables and data types I suggest that you read this article first. Let’s talk about PHP constants.

What Is Constant In PHP

As you may be guessing, the constant is a name or an identifier for a fixed value. Constants are just like variables but when they are defined they can’t be undefined or changed.

Constants are very useful for storing data that doesn’t change or that you don’t want to change by accident while your code is running. For example, constant could be configuration settings such as database username and password, website URL, company name, etc.

Constants are defined by using the PHP define() function. which accepts two arguments – the name of the constant and its value. When defined constant can be used at any time by referring to its name. Let’s look at the example:

<?php
// Defining constant
define("SITE_URL", "https://www.simplywebstuff.com/");
 
// Using constant
print 'Thank you for visiting - ' . SITE_URL;
?>

The output of the above code will be:

Thank you for visiting - https://www.simplywebstuff.com/

Naming Conventions for PHP Constants

The name of constants must follow the same rules as variable names, which means that a valid constant name must start with a letter or underscore, followed by any number of letters, numbers, or underscores. But here is a twist. You are not required to use the $ prefix for constant names.