Define Constant PHP

Constant in PHP ?

Constant are identifiers for a memory location Which Can be change according to requirement of program .In PHP Constant does NOT support interpolation . In PHP Constant must be in Upper Case eg. CONST  .To define Constant we have to use function define();

Syntax :
define(\’name of constant \’,\’ value of constant\’)
eg: define(\’PIE\’,\’3.14\’);
echo PIE;/// will result to 3.14

NOTE:Unlike variable  If we Try to define same Constant again then it throw a notice Already define.

 

Another way of Defining Constant is key word const .

eg:  const MIN_VALUE = 0.0;

echo   MIN_VALUE ; /// will result to 0

 

The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time.

Note : const cannot be used to conditionally define constants. It has to be used in the outermost scope

eg:

<?php

$x=10 and $y=10;
if ($x==$y) {
const CONST_VAL1 = \’CONST\’; // invalid produce error
}
// but
if ($x==$y) {
define(\’CONST_VAL2\’, \’CONST\’); // valid
}
echo CONST_VAL1; // produce error
echo CONST_VAL2;

?>

Scroll to Top