PHP Constant

In this PHP tutorial, you will learn all about constants in PHP. We will discuss in detail what is a constant, constant array, const keyword, naming conventions of constants, differences between constants and variables, magic constant, and mathematical constants.

What is a PHP Constant?

Constants are fairly similar to variables, but the values of constants cannot be modified or undefined. Constants are the names or the identifiers to store simple values which won’t be changed. The constant's values cannot be modified once it has been defined in the program. Constants are global by default, so we may use them everywhere we need throughout the script. Unlike variables, constants don't use the ‘$’ as the prefix. Constant may be defined in two ways:

  1. By using define() function
  2. By using the const keyword

Syntax


define(name, value, case-insensitive);  // using the define() function
const name = value;   // using the const keyword
 

How to define constants using define() function?

We use the define() function to define a constant in PHP. By using the define() function it defines a constant at run time. In the define() function, we pass the arguments ‘name’, ‘value’, and ‘case-insensitive’. The argument ‘case-insensitive’ is optional and by default, it will be false and if we want to define the constant name as case-insensitive we should pass the argument as true. By the convention we name the constant identifier in uppercase it is done to recognize constants and variables easily. Like the variables, we only use the alpha-numeric character and underscore for naming the constants and we won’t use the special characters and the white spaces. And all the constant names start with either alphabet or underscore.


define(“WELCOME”, “Welcome to learnetutorials.com”);  
echo WELCOME;
 

Output:


Welcome to learnetutorials.com

Example with case-insensitive value as true


define(“WELCOME”, “Welcome to learnetutorials.com”, true);  
echo welcome;
 

Output:


Welcome to learnetutorials.com

How to define constant using const keyword?

Like the define() function, we also use the const keyword to define a constant in PHP. By using the const keyword it defines constant at compile time. The const keyword is a language construct not a function like define(). By default, the constants defined using the const keyword are case-sensitive. By the convention we name the constant identifier in uppercase it is done to recognize constants and variables easily. Like the variables, we only use the alpha-numeric character and underscore for naming the constants and we won’t use the special characters and the white spaces. And all the constant names start with either alphabet or underscore.


const WELCOME =  “Welcome to learnetutorials.com”;  
echo WELCOME;
 

Output:


Welcome to learnetutorials.com

Example with case-insensitive value as true


const WELCOME =  “Welcome to learnetutorials.com”;  
echo welcome;
 

Output:


error

What is Constant Arrays in PHP?

We can also define a constant array in PHP. To define constant array we use the define() function. We use the constant array to define the array which should not be modified in the entire script. Defining the constant array is similar as defining the constants. We use the define() function with arguments ‘name’, ‘array’, and the ‘case-insensitive’.

Syntax


define(name, array, case-insensitive);  
 

Example:


define(“LANGUAGES”,[
   “PHP”,
   “Python”,
   “Java”
] );  
echo LANGUAGES[0];

 

Output:


PHP

Example with case-insensitive value as true


define(“LANGUAGES”,[
   “PHP”,
   “Python”,
   “Java”
], true);  
echo languages[0];

 

Output:


PHP

What is the use of constant() function in PHP?

The function constant() is used to return the value of the constant. This is beneficial when you want to access the value of a constant but don't know its name, for example, if it's stored in a variable or returned by a function.

Example


define(“AGE”,50);  // define a constant with name AGE
$AGE = 18;    // define a variable with name AGE
echo $AGE;  // print the value of the variable
echo constant(“AGE”); // print the value of the constant
 

Output:


18
50

What are the naming Conventions for PHP Constants?

  • The naming convention is mostly similar to the variable naming convention. The main difference is that the ‘$’ symbol is not used in the constant naming. 
  • By convention, constants are preferred to name the constant in uppercase letters.
  • A constant name in PHP will only contain the alphanumeric (a-z, A-Z, 0-9) character and the underscore (_). 
  • Every constant name must start with an alphabet (a-z, A-Z) or an underscore (_) in another hand, numeric (0-9) or special characters cannot be used.
  • A constant name should not contain a whitespace
  • If we are defining a constant using the define() function we can set it as case-insensitive or case-sensitive, or else if we are using the const keyword to define a constant then it will always be case-sensitive.

How to check whether if a PHP constant is defined in the script or not?

To check whether a constant is defined in the script or not we use the defined() function. In the defined() function we pass the constant name as the argument and if the constant is defined in the script it will return 1 (true) or otherwise it will return 0 (false).

Syntax


define(name, array, case-insensitive);  
 

Example:


define(“NAME”, “Jhon Doe”);
if(defined(NAME)){
    echo “The constant is defined”;
} else {
    echo “The constant is not defined”;
}
 

Output:


The constant is defined

Example with case-insensitive value as true


define(“FULL_NAME”, “Jhon Doe”);
if(defined(NAME)){
    echo “The constant is defined”;
} else {
    echo “The constant is not defined”;
}

 

Output:


The constant is not defined

How to use a variable as a constant name?

It is not always necessary to complicate a constant name in a program to the point where you want to access it. For example, if you may have a general-purpose program that you want to run on any number of distinct constants, not just the one you entered in the name for. The easiest method to fix this problem is to save the constant's name in a variable. To do so we have to assign the constant name into the variable and then when it is required we have to use the constant() function with the variable name as the argument.

Example :


define(“FULL_NAME”, “Jhon Doe”);
$name = “FULL_NAME”;
echo constant($name);
 

Output:


Jhon Doe

What are the differences between constants and variables?

Constants Variables
Once a constant is defined it can never be modified or undefined A variable can be modified or undefined whenever required
By default, the constants are global Variables can be local, static or global
Constants are defined using define() function or const keyword To define a variable nothing is needed just assign the value using the assignment operator (=)
Constants can be declared and retrieved from anywhere, regardless of variable scope rules Variables also can be declared anywhere but the variable scope rules are flowed
Constant doesn’t use the ‘$’ symbol Variables use the ‘$’ symbol as prefix to denote variable

What are PHP Script and Environment Related Constants / PHP Magic constants?

Magic constants are predefined constants in PHP that significantly change based on their use. They begin with a double underscore (__) and conclude with another double underscore. They are fairly similar to the other predefined constants, but because their values changes depending on the situation, they are referred to as magic constants.

There are 9 magic constants in PHP:
 

  1. __Line__

    It gives the current line number where the constant is invoked.

        <?php
            echo "Using  __LINE__ \n ";
            echo __LINE__;
        ?>
       
    

    Output:

      
      Using  __LINE__
      3
      
  2. __FILE__

    It is used to return the path where the file is stored.

        <?php
            echo "Using  __FILE__ \n ";
            echo __FILE__;
         ?>
      

    Output:

      
      Using  __FILE__
      C:\ xampp\htdocs\php\magic_constant.php
    
      
  3. __DIR__

    It is used to return the directory path of the executed file.

        <?php
            echo "Using  __DIR__ \n ";
            echo __DIR__;
        ?>
      

    Output:

      
      Using  __DIR__
      C:\ xampp\htdocs\php
    
      
  4. __FUNCTION__

    It is used to return the function name of the function where __FUNCTION__ constant is used.

        <?php
           echo "Using  __FUNCTION__ \n";
           function a(){
               echo __FUNCTION__;
           }
           a();
       ?>
    

    Output:

      
      Using  __FUNCTION__
      a
    
    
      
  5. __CLASS__

    It is used to return the class name of the class where __CLASS__ constant is used.

        <?php
           echo "Using  __CLASS__ \n";
           class a{
               function ab(){
                   ;
               }
           }
           class b{
               function ab(){
                   echo __CLASS__;
               }
           }
        $a = new a;
        $a -> ab();
        $b = new b;
        $b -> ab();
    
       ?>

    Output:

      
      Using  __CLASS__
      a
      
  6. __TRAIT__

    It is used to return the trait name of the trait where __TRAIT__ constant is used.

       <?php   
           echo "Using __TRAIT__ \n";    
           trait ab {    
               function abc(){    
                   echo __TRAIT__;  
               }    
           }    
           class xyz {    
               use ab;    
               }    
           $a = new xyz;    
           $a->abc();    
       ?>  
      

    Output:

      
      Using  __TRAIT__
      a
    
      
  7.  __METHOD__

    It is used to return the class method name of the class method where __METHOD__ constant is used.

        <?php   
           echo "Using __METHOD__\n";  
           class a {    
               function b() {    
                       echo __METHOD__ . "\n";   
                   }    
               function c(){    
                       echo __METHOD__;   
               }    
           }    
           $a = new a;    
           $a->b();
           $a->c();
       ?> 

    Output:

      
      Using __METHOD__
      a::b
      a::c
    
      
  8. __NAMESPACE__

    It will return the current namespace where it is used.

      <?php   
           echo "Using __NAMESPACE__\n";  
           class a {    
               function __construct() {    
                   echo 'This will be printed on calling namespace.';     
               }     
           }    
           $ab = __NAMESPACE__ . '\a';    
           $a = new $ab;   
       ?> 

    Output:

      
      Using __NAMESPACE__
            This will be printed on calling namespace.
    
      
  9. ClassName::class

    Like the other magic constant this does not begin and end with the double underscore (__). It is used to return the fully qualified name of the ClassName. PHP 5.5.0 introduces ClassName::class constant. It is useful when working with namespaced classes.

     <?php   
           namespace abc;  
           echo "Using ClassName::class \n";  
           class xyz {    
           }  
           echo xyz::class;    //ClassName::class   
       ?>

    Output:

      
      Using ClassName::class 
      abc\xyz
      

Which all are the Mathematical Constants in PHP?

Constant Value Description
INF INF It is used to return the infinity
M_E 2.7182818284590452354 It is used to returns the e
M_EULER 0.57721566490153286061 It is used to return Euler constant
M_LNPI 1.14472988584940017414 It is used to returns the natural logarithm of PI: log_e(pi)
M_LN2 0.69314718055994530942 It is used to returns the natural logarithm of 2: log_e 2
M_LN10 2.30258509299404568402 It is used to returns the natural logarithm of 10: log_e 10
M_LOG2E 1.4426950408889634074 It is used to returns the base-2 logarithm of E: log_2 e
M_LOG10E 0.43429448190325182765 It is used to returns the base-10 logarithm of E: log_10 e
M_PI 3.14159265358979323846 It is used to returns the value of Pi
M_PI_2 1.57079632679489661923 It is used to returns the value of Pi/2
M_PI_4 0.78539816339744830962 It is used to returns the value of Pi/4
M_1_PI 0.31830988618379067154 It is used to returns the value of 1/Pi
M_2_PI           0.63661977236758134308 It is used to returns the value of 2/Pi
M_SQRTPI 1.77245385090551602729 It is used to returns the square root of PI: sqrt(pi)
M_2_SQRTPI 1.12837916709551257390 It is used to returns 2/square root of PI: 2/sqrt(pi)
M_SQRT1_2 0.70710678118654752440 It is used to returns the square root of 1/2: 1/sqrt(2)
M_SQRT2 1.41421356237309504880 It is used to returns the square root of 2: sqrt(2)
M_SQRT3 1.73205080756887729352 It is used to returns the square root of 3: sqrt(3)
NAN NAN It is used to returns ‘Not A Number’
PHP_ROUND_HALF_UP 1 It is used to returns round halves up
PHP_ROUND_HALF_DOWN 2 It is used to returns round halves down
PHP_ROUND_HALF_EVEN 3 It is used to returns round halves even numbers
PHP_ROUND_HALF_ODD 4 It is used to returns round halves odd numbers