PHP Constants. Everything You Need To Know About PHP Constants

Posted by TotalDC

If you are reading this post, probably you maybe new to PHP and programming in general. And in that case if you need and intro into what is PHP variables and data types I suggest that you read this article first.

What Is Constant In PHP

As you maybe guessing, 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 you code is running. For example constant could be configuration settings such as database username and password, websites URL, company name etc.

Constants are defined by using 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. Lets look at the example:

// Defining constant
define("SITE_URL", "");
// Using constant
print 'Thank you for visiting - ' . SITE_URL;

The output of the above code will be:

Thank you for visiting -

Naming Conventions for PHP Constants

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 $ prefix for constant names.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: