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:
constis always case-sensitive, whiledefine()can be case-insensitiveconstcan only be used in the global scope, whiledefine()can be used anywhereconstis resolved at compile time, whiledefine()is resolved at runtime