PHP Constants
A constant is an identifier for a value that cannot change during script execution. PHP constants are defined using the define() function or, since PHP 7, with the const keyword outside of functions.
Unlike variables, constants do not use a $ sign before their name, and by convention are usually written in uppercase letters to distinguish them from regular variables.
define("NAME", value);
const NAME = value;Defining constants
define("NAME", value) creates a constant at runtime, while const NAME = value; is used at the top level or inside classes and is resolved at compile time.
Using constants
Once defined, a constant is accessed simply by its name, without a $ sign, and it is available globally throughout the script.
<?php
define("GREETING", "Hello!");
echo GREETING;
?>Hello!define() creates a constant that is used later without a $ sign.
<?php
const SITE_NAME = "MySite";
echo SITE_NAME;
?>MySiteconst declares a constant directly, commonly used at the top of a script or in a class.
Key points
- Constants are defined with define() or const.
- Constant names do not use a $ prefix.
- By convention, constant names are written in uppercase.
- Once set, a constant's value cannot change during execution.
