PHP Defining Constant



A. PHP Constant :

  1. Simple PHP Value can be represented using term called Constant.
  2. A value of constant cannot be change during the execution of the script.
  3. Constants are case-sensitive.
  4. Constant identifiers are always uppercase.
  5. Valid constant name in PHP starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  6. 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 :

  1. 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.
  2. Assignment Operator : Constants cannot be defined by using assignment operator. We need to use define() function to define constant.
  3. Cannot be modified : Once we define the constant, then constant cannot be redefined or modified.
  4. 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.