PHP Constants
Understanding unchangeable values in PHP
🔒 What are PHP Constants?
Constants are unchangeable values that remain the same throughout your script. Once defined, they cannot be modified or undefined, making them perfect for storing fixed configuration values.
<?php
// Define a constant
define("SITE_NAME", "My Website");
echo SITE_NAME; // Outputs: My Website
?>
Output:
My Website
Key Constant Concepts
define() Function
Traditional way to create constants using the define() function with name and value parameters.
<?php
define("PI", 3.14159);
echo PI;
?>
const Keyword
Modern way to define constants using the const keyword, available from PHP 5.3 onwards.
<?php
const MAX_SIZE = 100;
echo MAX_SIZE;
?>
Global Scope
Constants are automatically global and can be accessed from anywhere in your script without scope issues.
<?php
define("DB_NAME", "mydb");
function test() {
echo DB_NAME;
}
?>
Case Sensitivity
By default, constant names are case-sensitive. Use uppercase for naming convention and clarity.
<?php
define("NAME", "John");
// NAME and name are different
?>
🔹 Creating Constants
There are two main ways to create constants in PHP:
<?php
// Method 1: Using define()
define("GREETING", "Hello World");
echo GREETING; // Outputs: Hello World
// Method 2: Using const keyword
const APP_VERSION = "1.0.0";
echo APP_VERSION; // Outputs: 1.0.0
// Constants with arrays (PHP 7+)
define("COLORS", ["red", "green", "blue"]);
echo COLORS[0]; // Outputs: red
?>
Output:
Hello World
1.0.0
red
🔹 Constants vs Variables
Understanding the key differences between constants and variables:
<?php
// Variable - can be changed
$name = "John";
$name = "Jane"; // This works
echo $name; // Outputs: Jane
// Constant - cannot be changed
define("SITE_URL", "https://example.com");
// SITE_URL = "https://new.com"; // This causes an error!
echo SITE_URL; // Outputs: https://example.com
?>
Output:
Jane
https://example.com
🔹 Checking if Constant Exists
Use the defined() function to check if a constant has been defined:
<?php
define("STATUS", "active");
if (defined("STATUS")) {
echo "STATUS constant exists!";
} else {
echo "STATUS constant does not exist.";
}
// Check for undefined constant
if (defined("UNDEFINED_CONST")) {
echo "Found it!";
} else {
echo "Not found!";
}
?>
Output:
STATUS constant exists!
Not found!
🔹 Practical Examples
Real-world usage of constants in PHP applications:
<?php
// Database configuration
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASS", "password");
define("DB_NAME", "myapp");
// Application settings
const APP_NAME = "My Application";
const APP_ENV = "production";
const DEBUG_MODE = false;
// Using constants
echo "Connecting to " . DB_HOST;
echo "<br>";
echo "Application: " . APP_NAME;
echo "<br>";
echo "Environment: " . APP_ENV;
?>
Output:
Connecting to localhost
Application: My Application
Environment: production