What is PHP Constants?
In PHP, constants are like variables, but their values cannot be changed once they are defined. Constants are useful when you want to define a value that remains constant throughout the execution of the script, and you don’t want it to be accidentally altered later in the code.
To define a constant in PHP, you use the ‘define()’ function with the following syntax:
define("CONSTANT_NAME", value);
Here, CONSTANT_NAME is the name of the constant, and value is the data you want to assign to the constant. Note that constant names are usually written in uppercase by convention, though it is not required.
For example:
define("PI", 3.14159);
define("SITE_NAME", "My Website");
define("MAX_USERS", 100);
Once you define a constant, you can use it throughout your PHP script just like any other variable. The main difference is that you cannot reassign a new value to the constant. Attempting to do so will result in a warning or an error.
Constants can be used inside functions, classes, and even within conditional statements and loops.
Example of using a constant in PHP:
define("TAX_RATE", 0.10);
$price = 100;
$taxAmount = $price * TAX_RATE;
$totalPrice = $price + $taxAmount;
echo "Price: $price" . PHP_EOL;
echo "Tax Amount: $taxAmount" . PHP_EOL;
echo "Total Price: $totalPrice" . PHP_EOL;
Keep in mind that constants are always global in scope. They can be accessed from anywhere in the script, regardless of where they were defined. Also, constants are automatically case-sensitive, unlike variables, so be careful when using them.