The Constants In PHP

constant, as the name suggests is a portion of memory whose content does not change during the processing phase of our program in PHP. Unlike the variable, which once defined can change its value, the constant always remains the same and any “attempt” to change its value will produce an error.

To define a constant in PHP we use the define () function in this way:

define('CONSTANT_NAME','Text Here...');

The same observations made for the variables apply to the constants:

  • If string type values ​​are assigned, they must be enclosed in single quotes or double quotes;
  • If numeric values ​​are assigned, no quotes are needed.

A few examples:

define('NAME','Mr.Jon');
define('ADDRESS','USA');
define('AGE',25);

As a rule, the names of constants are usually written in upper case (but nothing prevents you from using lower case). Note that the names of the constants, exactly as happens in the variables, are case-sensitive , so pay attention to the use of upper and lower case in the name of the constant.

It is also possible to define case-insensitive constants, in which case it will be sufficient to specify ‘true’ as the third parameter in the define () function :

<?php 
//define constant
define('NAME','Mr.Jon ');
define('address','USA ');
define('AGE',25);

//print constant
echo NAME;
echo address;
echo AGE;
?>

As we have seen in the example above, the constant is used in the PHP code simply by its own name without, that is, the dollar sign which is typical of variables.

Another difference with variables is that constants are always accessible within the program functions (while variables are only accessible if imported via global ).

Leave a Comment