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 :
<?php
define(“ConstantName”, “value”);
?>
constant() function
constant function used to retrieve the constant value by using the constant name.
constant(“constantname”);
Example of php constant
<?php
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
<?php
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