Home >Backend Development >PHP Tutorial >Detailed explanation of the difference between the use of const and define in php_PHP tutorial
1. Const is used to define class member variables. Once defined, its value cannot be changed. define defines global constants that can be accessed anywhere.
2. define cannot be defined in a class but const can.
3. Const cannot define constants in conditional statements
if (...) {
const FOO = 'BAR'; // invalid
}
but
if (...) {
define('FOO', 'BAR'); // valid
}
4. const uses an ordinary constant name, and define can use an expression as the name.
const FOO = 'BAR';
for ($i = 0; $i < 32; ++$i) {
define('BIT_' . $i, 1 << $i);
}
5. const can only accept static scalars, while define can use any expression.
const BIT_5 = 1 << 5; // invalid
but
define('BIT_5', 1 << 5); // valid
6. const is always case-sensitive, but define() can define case-insensitive constants through the third parameter
define('FOO', 'BAR', true); www.2cto.com
echo FOO; // BAR
echo foo; // BAR
Summary:
Using const is simple and easy to read. It is a language structure in itself, while define is a method. Using const to define is much faster than define at compile time.
Excerpted from aa705123123’s column