What’s the difference between define and const in php?

In this post, we give you the difference between const and define in PHP.

1. Compare define() vs const:

As we know both define() and const are used to declare a constant in PHP script.

Let’s discuss the difference between these two.

Define Const
1.Syntaxdefine(‘SOL’, ‘SOLTUTS’);const SOL= ‘SOLTUTS’;
2. Rundefine() defines them at run time. define()s are slow when using a large number of constants.const defines constants at compile time, they are a bit faster than define()s.
3. Conditional blocksWe can use the define() keyword to declare constant in conditional blocks:
EX:
if (/* some condition */) {
define(‘SOL’, ‘SOLTUTS’); //valid
}
We can’t use the const keyword to declare constant in conditional blocks:
EX:
 if (/* some condition */) {
const SOL = 'SOLTUTS'; // CANNOT DO THIS!
}
4. Expressiondefine() takes any expression.
Ex:
define(‘BIT_5’, 1 << 5); // always valid
for ($i = 0; $i < 32; ++$i) {
define(‘BIT_’ . $i, 1 << $i);
}
define(‘CONST’, 4 * 3); // always valid
const accepts a static scalar (number, string or other constant like true, false, null, __FILE__). Since PHP 5.6 constant expressions are allowed in const as well.
Ex:
const BIT_5 = 1 << 5; // valid since PHP 5.6, invalid previously.
const FOO = 4 * 3; // valid since PHP 5.6, invalid previously.
5. Case sensitivedefine() allows you to define case insensitive constants by passing true as the third argument.
Ex:
define(‘SOL’, ‘SOLTUTS’, true);
echo SOL; // SOLTUTS
echo sol; // SOLTUTS
consts are always case sensitive.
Ex:
const SOL= 2;
const sol = 3;
echo SOL; // 2
echo sol; // 3
6. Utilized within a classdefine() can’t be utilized within a class or interface to declare a class constant or interface constant.
Ex:
class Soltuts{  
    define(‘SOL’, 2); // invalid      
echo SOL; // invalid  
 }
const can also be utilized within a class or interface to declare a class constant or interface constant
Ex:
class Soltuts{    
  const SOL= 2; // valid      
echo SOL; // valid  
 }
7. Arraysdefine() does not support arrays yet. Arrays will be supported in PHP 7.
Ex:
define(‘FOO’, [1, 2, 3]); // invalid in PHP 5.6, valid in PHP 7.0
const constants can also be arrays.
Ex:
const SOL = [1, 2, 3]; // valid in PHP 5.6
8. Namespace define() has to be passed the full namespace name:
Ex:
namespace A\B\C; // To define the constant A\B\C\SOL:
define(‘A\B\C\SOL’, ‘SOLTUTS’);
const defines a constant in the current namespace.
Ex:
namespace A\B\C; // To define the constant
A\B\C\SOL:
const SOL= ‘SOLTUTS’;