PHP Constants

PHP Constants

PHP Constants


Suppose we have a variable that should not change its value in all project, we can define a variable for it, but it is not correct, because we can change it by accident in the project. For it, Php has constants.

Constants are the names of a value that does not change during the execution of the program.

In order to create a constant, we use to define a () function, in the following format.

  define (name, value, caseSensitive)

where:

name - is a name of constant, which must comply with the same rules as the other names in PHP.

value - the value of constant.

caseSensitive - Optional parameter, it specifies whether the constant name should be case-insensitive (true) or not (false).

<?php
   define("pi", 3.14, true);
  
   echo(pi);
   // output 3.14

   echo (PI);
   // output 3.14

?>

Constants are like variables except.

  • Constants have not $ sign
  • Constants can be defined only by using the define () function, instead of assigning values
  • Constants can be defined and accessed anywhere in project, which means that they are automatically global
  • Constants cannot change value, after defining
Note:

  Be careful, with the name of constants, __NAME__, is valid name for constant, but php have some Magic Constants, that is like __constantName__ syntax, and if one day php provides a magical constant __NAME__ that will break your script.

About magical constants we will talk later.


Reactions

Post a Comment

0 Comments

close