PHP Constants with Examples

A constant is PHP is a name or an identifier for a value which remains fixed and never change throughout the program.

In other words, a constant is a variable whose value does not change at runtime after being defined. For example, if you need to define the value of PI (i.e. 3.14) in a PHP program, you can use a constant to store its value.

This is because the value of PI is a fixed number that does not change during the execution of the program. By default, constants are case-sensitive in PHP. They are always written in the uppercase letters.

Constants are automatically global in PHP, meaning they are accessible throughout the entire script or program, regardless of where they are defined.

Once a constant is defined, you can use it in any function, class, or file with no need of any special keyword or global declaration. We mainly use constants for storing values that need to be accessed across different parts of the application.

Rules for Naming Constants in PHP


There are certain rules for defining a constant in PHP that you should follow them. They are as:

  • A constant name must start with letters, numbers, and underscores.
  • It does not start with a numeric digit.
  • Constant names can contain alphabetic characters, digit from 0 to 9, and underscores (_).
  • A constant name cannot contain space. If a constant name consists of more than one word, you must use the underscore (_) character to separate it.
  • By default, constant names are case-sensitive. It should be written in the uppercase letters. For example, VALUE. However, you can make them case-insensitive by passing true as the third argument in the define() function.

Valid Constant Names in PHP

Some of the valid constant names in PHP are as follows:

  • COUNT_9 // Valid because constant name can start with alphabetic character.
  • _ACCOUNT // Valid because a constant name can start with an underscore character.
  • MY_ACCOUNT // Valid because we can use an underscore to separate more than one word.
  • ACCOUNT // Valid because constant must be written in the uppercase letter.

Invalid Constant Names in PHP

Some of invalid constant names in PHP are as follows:

  • 8_COUNT // Invalid because a constant name cannot start with a numeric digit.
  • COUNT# // Invalid because a constant name cannot have a hash symbol (#).

Syntax for Defining PHP Constants


There are two ways by which you can define constants in PHP. They are:

  • define() Function
  • const Keyword

Using define() Function

To define constants in PHP, you can use the define() function provided by PHP. The define() function accepts two or three arguments as per your requirement.


The general syntax to define a constant using define() function is as follows:

define("CONSTANT_NAME", "Value"); // two arguments.
define("CONSTANT_NAME", "Value", case-insensitive); // three arguments.

In the above syntax,

  • define() is the predefined function used to define constant.
  • CONSTANT_NAME represents the name of the constant.
  • Value specifies the value of the constant. It can be integer, boolean, string, float, NULL, and array type.
  • case_insensitive: This is the third argument which is an optional. By default, it is false, but you can set to true for using a constant name in any case (lowercase or uppercase).

Let’s take some basic examples in which we will define constants using define() function.

Example 1:

<?php
// Defining a constant.
define('SITE_NAME', 'Scientech Easy');
echo SITE_NAME;
?>
Output:
      Scientech Easy

In this example, we have used the define() function to define a constant. SITE_NAME is the name of constant and Scientech Easy is a string type value of the constant. Then, we have accessed it to display the value on the browser or console.

Let’s take another example in which we will define case-insensitive constants.

Example 2:

<?php
// Defining a case-insensitive constant.
define('DB_HOST', 'localhost', true);
echo db_host;
?>
Output:
      localhost

Note: Defining “case-insensitive constants” is deprecated since PHP 7.3.

Using const Keyword

PHP also provided a keyword const that is used to define constants within classes, interfaces, or namespaces. The const keyword defines a constant at compile time, which means that the value must be initialized when the program is written, not at runtime.

The const keyword is a language construct, not a function. The constant defined using const keyword is case-sensitive. The general syntax to define a constant with const keyword is as follows:

const CONSTANT_NAME = value;

Example 3:

<?php
// Defining a constant with const keyword.
const PI = 3.14159;
echo PI;
?>
Output:
      3.14159

PHP Constant Arrays


In PHP 7.0 and later, you can define an array constant using the define() function, but not with the const keyword. The const keyword only supports scalar type values, such as integers, floats, strings, and booleans, but does not support array values.

Example 4:

<?php
// Defining an array constant with values.
define('FRUITS', ['Apple', 'Banana', 'Cherry']);

// Accessing the array constant
echo FRUITS[0];
echo "\n"; 
echo FRUITS[1];
echo "\n"; 
echo FRUITS[2];
?>
Output:
      Apple
      Banana
      Cherry

Constants are Global


Constants are automatically global in PHP, which means that you can use them across the entire script or program, regardless of where they are defined.

Example 5:

<?php
define("GREETING", "Welcome to ScientechEasy.com!")

// Defining a function.
function myTest() {
   echo GREETING;
}
myTest(); // Calling function.
?>
Output: 
      Welcome to ScientechEasy.com!

Constant() function


So far, you have directly used the constant name to return or print the value of a constant in the above examples. You can also do the same thing with the help of constant() function. Look at the example below.

Example 6:

<?php
define("GREETING", "Welcome to ScientechEasy.com!");
echo constant("GREETING");
?>
Output:
     Welcome to ScientechEasy.com!

In the given example, we have used the constant() function that returns the constant value where GREETING is the constant name whose value is to be returned.

Best Practices for Using Constants


There are the following key points for defining constants that you should keep in mind. They are as:

  • Always write the meaningful constant names that convey the purpose of the constants. For example, use MAX_USERS instead of just MAX.
  • Write constant names in uppercase letters with underscores separating words. For example, DB_NAME and SITE_URL.
  • Avoid case-insensitive constants.
  • Always use case-sensitive names.
  • When you define constants within a class, prefer using the const keyword.
  • Use constants for values that should remain unchanged throughout the program execution.

Common Errors When Using Constants


1. When you try to access a constant that hasn’t been defined, the Undefined Constant Error occurs.

echo UNDEFINED_CONSTANT; // Warning: Use of undefined constant.

2. When accessing constant names, one should not enclose them in quotes.

define('MAX_USERS', 100);
echo "MAX_USERS"; // Outputs: MAX_USERS

Use the constant name without quotes.

3. You cannot use the const keyword to define constants conditionally or inside functions.

if (true) {
    const MAX_VALUE = 100; // Error
}

Use the define() function for dynamic or conditional definitions.

PHP Constants vs. Variables


FeatureConstantsVariables
MutabilityImmutable, meaning that you cannot be changed once defined.Mutable, meaning that it can be changed throughout the script.
ScopeBy default, constants are global.Variables can be local, global, or static.
Syntaxdefine(‘CONSTANT’, value) or const NAME$variable_name
Naming ConventionUppercase by conventionLowercase by convention
UsageUsed for fixed values.Used for values that may change.

Practical Applications of PHP Constants


(1) Database Configuration:

You can define the database credentials as constants because they remain immutable and globally accessible.

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'password');
define('DB_NAME', 'example_db');

(2) Application Settings:

You can use constants to define application settings that should not change during execution.

define('APP_ENV', 'production');
define('DEBUG_MODE', false);

(3) Mathematical Constants:

You can use the constants like PI, EULER, etc., for mathematical calculations to prevent accidental modifications.


In this tutorial, we have discussed PHP constants that provide a powerful way to define values that remain unchanged throughout the script or program execution. They enhance the readability and maintainability of the code by preventing accidental modifications to critical values. I hope that you will have understood the basic concepts of defining constants in PHP and practiced all examples based on them.