Constants in PHP

We already learned about variables. I assume you would have a clear idea about variables. As we know the value of a variable can be changed numerous times throughout the program. but on the other hand value of constants can not change. Constants are also used to store data like variables but once constants get initialized values can not be changed.

With the help of constants, we have stored data that would not change in the whole program for example store data like DB_username, DB_password, or BASE_URL in constants. Constants help us to make sure that our data would not change throughout the whole program even if not by mistake by the programmer.

If you define a constant in a program the only way to change the value is to change the value where you define the constant for the very first time in the program.

In PHP we can define constants using the define() function. This function accepts two parameters first one is the name of the constant and the second is the value of the constant. After defining the constant you can access it anywhere in the program by using its name. Please check the following example program to understand constants more clearly.

//defining constant Here
define("language", "PHP");
//accessing constant with name
echo 'I Love ' . language;


Spread the love
Scroll to Top