Constants are similar to variables, but once defined, their values cannot be changed or undefined throughout the script.
PHP Constants
A constant is a name for a simple value that remains the same during the script’s execution. A valid constant name starts with a letter or underscore (without a $ sign). Unlike variables, constants are automatically global across the entire script.
Creating a PHP Constant
To create a constant, use the define() function.
Syntax
define(name, value);
Parameters:
- name: Specifies the constant’s name.
- value: Specifies the constant’s value.
Example: Case-Sensitive Constant
define("WELCOME_MESSAGE", "Welcome to BikeZone!");
echo WELCOME_MESSAGE;Using the const Keyword
You can also create a constant using the const keyword.
Example: Case-Sensitive Constant with const Keyword
const BRAND = "Harley-Davidson"; echo BRAND;
const vs. define()
constcannot be created inside a block scope, such as within a function or an if statement.definecan be created inside a block scope.
PHP Constant Arrays
From PHP 7 onwards, you can create an array constant using the define() function.
Example: Creating an Array Constant
define("BIKE_BRANDS", [
"Harley-Davidson",
"Yamaha",
"Ducati"
]);
echo BIKE_BRANDS[0];Constants are Global
Constants are automatically global and can be used across the entire script.
Example: Using a Constant Inside a Function
define("GREETING", "Welcome to BikeZone!");
function displayGreeting() {
echo GREETING;
}
displayGreeting();

