PHP Constants

constants are like variables except that, once assigned a value they can't be changed.

a constant value cannot change during the execution of the script.


PHP Constant

a valid constant name starts with a letter or underscore( _ ) no $ sign before the constant name.

the scope of a constant is global. you can access constants anywhere in your script without regard to scope.


php define()  a  constants

you can define a constant by using the define() method.

syntax:

          define(constant_name, value, case)     
  • constant_name : the name of the constant.
  • value : the value of the constant.
  • case : true(case-insensitive)/false(case-sensitive).

note: case-insensitive constants are stored as lower-case.

 <?php
       
         define("name", "sandeep kumar nehra");
                      
         define("xxxx","this is null",false);
                      
         define("all", "sandeep kumar nehra",true);
                      
         echo  name."<br/>";
                      
         echo  xxxx."<br/>";
                      
         echo  all."<br/>"; 
                      
         echo  all."<br/>";      //Case-insensitive constants are stored as lower-case
                      
 ?>              

note : constants may only contain scalar values such as boolean, integer, float, and string (not values such as arrays and objects).


PHP :- differences between constants and variables

  • constants do not have a dollar sign ($) before them.
  • constants may only be defined using the define() method, not by simple assignment.
  • constants may be defined and accessed anywhere without regard to variable scoping rules.
  • constants may not be redefined and not its value changed during execution.
  • constants may only evaluate to scalar values (bool, integer, float, string).