Constants in PHP

By | April 5, 2020

In this tutorial, we will learn about Constants in PHP. In the last tutorial, we learnt about variables in PHP. I hope now you would have a clear idea about variables. As we learnt in the last tutorial value of a variable can be changed throughout the program. but on the other hand value of constants can not change. In simple words, constants are also like variables but once constants get defined value of constants can not be change like variables.

With the help of constants, we have store data which 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 not by mistake from the Programmer.

If you define any value in from Constant. The only way to change value is to change value where you define the constant for the very first time in the program.

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

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