Google News
logo
PHP Program to Use a constant inside a function (when it is defined outside the function)
In PHP, you can use a constant inside a function even if it is defined outside the function by simply referencing the constant by its name.

Here's an example :
Program :
<?php
define('TAX_RATE', 0.075);

function calculateTax($price) {
    $tax = $price * TAX_RATE;
    return $tax;
}

$subtotal = 100;
$tax = calculateTax($subtotal);
$total = $subtotal + $tax;

echo "Subtotal: $subtotal\n";
echo "Tax: $tax\n";
echo "Total: $total\n";
?>
Output :
Subtotal: 100
Tax: 7.5
Total: 107.5
In this example, a constant named `TAX_RATE` is defined outside the `calculateTax()` function using the `define()` function. The `calculateTax()` function takes a price as a parameter and calculates the tax using the `TAX_RATE` constant.

The `calculateTax()` function is then called with a subtotal of 100. The tax is calculated using the `TAX_RATE` constant and added to the subtotal to get the total.

Finally, the `echo` statements output the values of the subtotal, tax, and total.

Note that constants are automatically global in PHP, so you can access them from any part of your code.