PHP Constants: A Comprehensive Guide

Learn how to define and use constants in PHP along with practical examples and best practices.

📌 1. Defining a Constant

A constant is an identifier (name) for a simple value. Unlike variables, constants cannot be changed or undefined once they have been set during script execution. In PHP, you can define a constant using the define() function or the const keyword.

Case-sensitive Constant Name

<?php
// Defining a case-sensitive constant
define("GREETING", "Welcome to Brijesh Patel's Tech Guide!");

echo GREETING;
?>

🚀 2. Using the const Keyword

The const keyword is often preferred because it defines constants at compile time compared to define() which defines them at run time. It generally offers better readability and performance.

<?php
const SITE_NAME = "brijesh.work";

echo "Visit " . SITE_NAME . " for more tutorials!";
?>

📦 3. Creating an Array Constant

PHP also supports array constants. You can create an array constant using either the define() function (PHP 7.0+) or the const keyword (PHP 5.6+).

<?php
define("SUPPORTED_LANGUAGES", [
    "PHP",
    "JavaScript",
    "Python",
    "Go"
]);

echo "I love coding in " . SUPPORTED_LANGUAGES[0] . "!";
?>

🌍 4. Constants Inside Functions

Unlike standard variables, constants are automatically global and can be used directly across the entire script without needing the global keyword.

<?php
define("DB_HOST", "localhost");

function connectDatabase() {
    // We can access DB_HOST directly inside the function
    echo "Connecting to database at " . DB_HOST . "...";
}
 
connectDatabase();
?>

⚠️ 5. Case-insensitive Constants (Deprecated)

Deprecated Warning: Defining case-insensitive constants by passing true as the third parameter to define() has been deprecated as of PHP 7.3.0 and removed in PHP 8.0.0. You should avoid this practice.
<?php
// NOT RECOMMENDED: The third parameter enabled case-insensitivity
// This will throw a deprecation warning in PHP 7.3+ and a fatal error in PHP 8.0+
define("OLD_GREETING", "Hello World!", true);

echo old_greeting; 
?>