PHP Constants

Constants in PHP are identifiers that represent fixed values that cannot be changed during script execution. They are defined using the define() function or the const keyword.

Defining Constants

<?php
// Using define() function
define("GREETING", "Hello World!");
define("PI", 3.14159);

// Using const keyword
const MAX_USERS = 100;
const APP_VERSION = "1.0.0";

// Using constants
echo GREETING . "\n";
echo PI . "\n";
echo MAX_USERS . "\n";
echo APP_VERSION . "\n";
?>

Output:

Hello World!
3.14159
100
1.0.0

Constant Arrays

<?php
// Defining constant array using define()
define("ANIMALS", [
    "dog",
    "cat",
    "bird"
]);

// Defining constant array using const
const FRUITS = [
    "apple",
    "banana",
    "orange"
];

// Accessing constant arrays
print_r(ANIMALS);
print_r(FRUITS);
?>

Key Differences between define() and const:

  • const is always case-sensitive, while define() can be case-insensitive
  • const can only be used in the global scope, while define() can be used anywhere
  • const is resolved at compile time, while define() is resolved at runtime