A constant is a fixed value that cannot be changed after being set. Unlike variables, constants do not use $
and are global by default.
define()
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite
2️⃣ Using const
const PI = 3.14159;
echo PI; // Outputs: 3.14159
🚀 Note: const
cannot be used inside functions, while define()
can.
Accessing Constants Inside Functions
define("GREETING", "Welcome!");
function sayHello() {
echo GREETING;
}
sayHello(); // Outputs: Welcome!
PHP has built-in constants like:
echo PHP_VERSION; // Outputs the PHP version
echo PHP_OS; // Outputs the OS name
✔ Constants cannot be changed once defined.
✔ Use define()
or const
to create them.
✔ They are global and accessible anywhere. 🚀