PHP Defining Constant
A. PHP Constant :
- Simple PHP Value can be represented using term called Constant.
- A value of constant cannot be change during the execution of the script.
- Constants are case-sensitive.
- Constant identifiers are always uppercase.
- Valid constant name in PHP starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
- Value of constant cannot be changed once defined.
B. How to define PHP Constant ?
We need to use define() function to define constant. Like suppose we need to define two constant i.e MAX and MIN then we can write it as -
define("MAX", 50); define("MIN", 80);
Now we have defined constant, in order to retrieve the value of constant we can simply use the name of constant.
echo MAX; echo MIN;
Alternate way of accessing the value of constant is using constant() function.
echo constant("MAX"); echo constant("MIN");
C. PHP Defining Constant : Example
<!DOCTYPE html> <html> <body> <?php define("MAX", 50); define("NUM", 10.502); define("MSG", "Hello PHP"); echo MAX . "<br />"; echo NUM . "<br />"; echo MSG . "<br />"; //Alternate Way echo constant("MAX") . "<br />"; echo constant("NUM") . "<br />"; echo constant("MSG") . "<br />"; ?> </body> </html>
Output :
50 10.502
Tips of Using the PHP Constants :
- Using Dollar Sign : No need to use dollar sign ($) before a constant like variables. We can access the constants just by writing the name of constant.
- Assignment Operator : Constants cannot be defined by using assignment operator. We need to use define() function to define constant.
- Cannot be modified : Once we define the constant, then constant cannot be redefined or modified.
- Scope : Constants can be accessed from anywhere. Variable scoping rules are not applicable to PHP constants.
In the next tutorial we are going to learn PHP magic constants.