Constant in PHP

PHP Constant

PHP constant is same as variable but we never change constant value during the execution of program.
We can use constant only when we use single value at multiple place in our program.
PHP constants storage are permanent while variables are temporary storage.

Constant cannot be defined like variable, they only be defined using define() function.Once the constants are defined then it never be redefined or changed.

PHP constants are defined using the define() function with two arguments.
first the name of constant and its value.

Constants name are case sensitive and name always start with a letter or underscore.
Constant name must be in uppercase letter.
Constants name do not required $ sign for constant name.

 PHP constants syntax :


define(“ConstantName”, “value”);


constant() function

constant function used to retrieve the constant value by using the constant name.


Example of php constant


define(“MYNAME” , “Meera”);

echo MYNAME;
echo constant(“MYNAME”);


In above php example we create a constant “MYNAME” and assign value “Meera” using define() function.
The echo MYNAME and echo constant(“MYNAME”) both line are same.

Example of sum of two constant


define(“A” ,10 );
define(“B”, 15);

define(“SUM”, A+B);
echo “The sum of A and B = ” . SUM;

//echo A+B;

//echo constant(“A”) + constant(“B”);


The output is :
The sum of A and B = 25

Leave a Reply

Your email address will not be published. Required fields are marked *