PHP Constants

In PHP, constants are used to define values that remain unchanged throughout the execution of a script. Once defined, constants cannot be modified or redefined. They are typically used for storing configuration values, fixed values, or global constants that are required across different parts of a PHP application.

Create a PHP Constant

Syntax : define(namevaluecase-insensitive)


  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

Here’s the syntax for defining a constant in PHP:

define("CONSTANT_NAME", "constant_value");

The define() the function is used to define a constant. It takes two arguments: the name of the constant (as a string) and its value. By convention, constant names are usually written in uppercase.

Here’s an example that demonstrates the usage of constants in PHP:

define("SITE_NAME", "My Website");
define("MAX_USERS", 100);

echo SITE_NAME;  // Output: My Website

$maxAllowedUsers = MAX_USERS;
echo $maxAllowedUsers;  // Output: 100

In this example, we define two constants: SITE_NAME with the value “My Website” and MAX_USERS with the value 100. We then use the constants in our code by referencing their names. Constants are accessed without the leading dollar sign ($), unlike variables.

Some important points to note about PHP constants:

  1. Constants are case-sensitive by default. For example, CONSTANT_NAME and constant_name would be treated as two different constants.
  2. Constants are automatically global and can be accessed from anywhere within the PHP script, regardless of scope.
  3. Constants can hold various types of values, including strings, numbers, booleans, and arrays.
  4. Constants cannot be redefined or undefined once they are defined. Attempting to redefine a constant will result in a warning or error.

Using constants can help improve code readability, reduce the risk of accidental value changes, and make it easier to manage configuration values throughout your PHP application.