How to use the const keyword in PHP?

Member

by adan , in category: PHP General , a year ago

How to use the const keyword in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lottie , a year 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.

Member

by deron , 4 months ago

@adan 

In addition to the method described above, the const keyword can also be used within a class to define class constants. To define a class constant, you can follow the syntax below:


1 2 3


class ClassName { const CONSTANT_NAME = value; }


For example, to define a class constant named MAXIMUM_QUANTITY with a value of 10, you would use the following code:


1 2 3


class Product { const MAXIMUM_QUANTITY = 10; }


You can access a class constant using the scope resolution operator (::) followed by the constant name. For example, to access the MAXIMUM_QUANTITY constant in the Product class, you would use the following code:


1


echo Product::MAXIMUM_QUANTITY; // Output: 10


Class constants are useful when you want to define values that are associated with a class and are shared a**** all instances of that class. They can be used for things like default values, minimum/maximum limits, or fixed values that should not be changed.