How to use the const keyword in PHP?

Member

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

How to use the const keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 6 months ago

@adan 

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:

1
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:

1
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:

1
2
3
$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.