How to use the const keyword in PHP?


by adan , in category: PHP General , 6 months ago

How to use the const keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer


by lottie , 6 months ago


In PHP, the const keyword is used to define a constant, which is a value that cannot be changed during the execution of a script.

To define a constant in PHP using the const keyword, you can follow the syntax below:

const CONSTANT_NAME = value;

For example, to define a constant named TAX_RATE with a value of 0.08, you would use the following code:

const TAX_RATE = 0.08;

Once defined, you can use the constant in your code like a regular variable, but you cannot change its value. For example, you can use the TAX_RATE constant in a calculation like this:

$price = 100;
$total = $price * (1 + TAX_RATE);
echo $total; // Output: 108

Note that constant names in PHP are case-sensitive by default, and it is a common convention to use all uppercase letters for constant names to distinguish them from variables.