Here is an example of defining and using a constant in PHP:
define("PI", 3.14159);
echo PI; // Output: 3.14159
In this example, the define() function is used to create a constant named PI with a value of 3.14159. The constant is then printed to the screen using the echo statement.
It’s important to note that constant names are case-sensitive in PHP, and they cannot be redefined once they have been declared.
You can also define constants using the const keyword:
const GREETING = "Hello, world!";
echo GREETING; // Output: Hello, world!
In this example, the const
keyword is used to define a constant named GREETING
with a value of "Hello, world!"
. The constant is then printed to the screen using the echo
statement.
Constants can also be used in functions:
define("TAX_RATE", 0.08);
function calculate_tax($amount) {
return $amount * TAX_RATE;
}
$subtotal = 100;
$total = calculate_tax($subtotal) + $subtotal;
echo $total; // Output: 108
In this example, the TAX_RATE
constant is defined with a value of 0.08
. The calculate_tax()
function uses the constant to calculate the tax on a given amount, which is then added to the subtotal to calculate the total. The resulting value is then printed to the screen using the echo
statement.
By using constants in PHP, you can store and access frequently used values throughout your script without having to repeatedly define them or risk accidentally changing their values during runtime.