PHP

🔒 What Is a Constant in PHP?

A constant is an identifier (name) for a simple value that cannot be changed or undefined during the execution of the script. Unlike variables, once a constant is assigned a value, it remains fixed throughout the entire application lifecycle.

  • In Short: Constant = Assigned once, unchangeable, and globally accessible data holder (e.g., site domain, API keys, database settings).

🛠️ How Are Constants Defined in PHP?

PHP provides two distinct methods for declaring constant values:

  • Using the define() function (Runtime definition)
  • Using the const keyword (Compile-time definition)

PHP
// Method 1: Using define() function
define("SITE_NAME", "teachwebcode.com");

// Method 2: Using const keyword
const MAX_USERS = 100;

echo SITE_NAME; // Outputs: teachwebcode.com
echo MAX_USERS; // Outputs: 100

📌 Basic Rules for PHP Constants

1️⃣ Must Start with a Letter or Underscore
Constant names cannot start with numbers. By convention, constant names are written in ALL_CAPS.

  • ✔️ SITE_NAME or _CONFIG
  • 1SITE (Invalid)

2️⃣ Valid Characters Only
Names can contain letters (A–Z, a–z), numbers (0–9), and underscores (_). Special characters, spaces, or non-ASCII characters should be avoided.

3️⃣ Reserved Keyword Protection
You cannot name constants using PHP's predefined keyword names or global magic constants.

4️⃣ Case-Sensitivity
Constant identifiers are case-sensitive by default. For example, SITE and site refer to two completely different identifiers.

5️⃣ Single Definition & Unchangeable Value
Once defined, a constant cannot be redefined, overwritten, or removed using unset().

PHP
define("VERSION", "1.0.0");

// Trying to overwrite triggers a Notice/Warning:
define("VERSION", "2.0.0"); // ❌ Constant VERSION already defined

6️⃣ Global Scope Accessibility
Constants are automatically global and can be accessed across the entire script, including inside classes, functions, or included files, without needing the global keyword.

PHP
define("DB_NAME", "my_database");

function connectDatabase() {
    // Accessible inside functions without 'global' keyword
    echo "Connecting to " . DB_NAME;
}

connectDatabase();

  • 📝 Brief Summary

  • Constants hold immutable values that cannot be altered or redefined once set.
  • They are defined using define() or const and bypass standard variable scope limitations.
  • Ideal for storing application configurations, site titles, base URLs, and system constants.