How to Define a Constant in PHP with define()

In PHP, constants are identifiers for simple values that cannot change during the execution of a script. This article provides a quick and clear guide on how to define constants using the built-in define() function, explaining its syntax, rules, and practical code examples to help you implement them in your PHP applications.

Syntax of the define() Function

The define() function is used to create a named constant at runtime. The syntax is straightforward:

define(string $name, mixed $value): bool

Basic Example of PHP define()

To define a constant, pass the name of the constant as a string and its corresponding value. Unlike variables, constants do not start with a dollar sign ($).

<?php
// Defining a string constant
define("SITE_NAME", "My Awesome Website");

// Defining an integer constant
define("MAX_LOGIN_ATTEMPTS", 5);

// Accessing the constants
echo SITE_NAME; // Outputs: My Awesome Website
echo MAX_LOGIN_ATTEMPTS; // Outputs: 5
?>

Key Rules and Characteristics of PHP Constants

When using the define() function, keep the following rules in mind:

  1. Naming Convention: Constant names must start with a letter or an underscore, followed by any number of letters, numbers, or underscores. By convention, constant names are written in uppercase to distinguish them from variables.
  2. No Dollar Sign: Do not use a $ before the constant name when defining or referencing it.
  3. Global Scope: Constants are automatically global. They can be accessed from anywhere in your PHP script, including inside functions, classes, and loops, without using the global keyword.
  4. Immutable: Once a constant is defined, it cannot be changed or redefined later in the execution.
  5. Case Sensitivity: Since PHP 8.0, constants are strictly case-sensitive. The third parameter of define() (which allowed for case-insensitivity) has been deprecated and removed.

Defining Array Constants

Since PHP 7.0, you can also define array constants using the define() function:

<?php
// Defining an array constant
define("ALLOWED_ROLES", [
    "admin",
    "editor",
    "author"
]);

// Accessing array elements
echo ALLOWED_ROLES[0]; // Outputs: admin
?>

Checking if a Constant is Defined

To prevent errors when defining a constant that might already exist, you can use the defined() function to check for its existence:

<?php
if (!defined("API_KEY")) {
    define("API_KEY", "12345-abcde");
}
?>