【Ask】When defining constants in PHP, what is the difference between const and define?
【Answer】Using const makes the code simple and easy to read. Const itself is a language structure, while define is a function. In addition, const is much faster than define during compilation.
(1).const is used for the definition of class member variables. Once defined, it cannot be modified. define cannot be used for the definition of class member variables, but can be used for global constants.
(2).const can be used in classes, define cannot.
(3).const cannot define constants in conditional statements.
For example:
if (...){
const FOO = 'BAR'; // invalid invalid
}
if (...) {
define('FOO', 'BAR' ); // Valid valid
}
(4).const uses an ordinary constant name, 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 take any expression.
For example:
const BIT_5 = 1 << 5; // Invalid invalid
define('BIT_5', 1 << 5); // Valid valid
(6).const definition The constants are case-sensitive, and define can specify whether it is case-sensitive through the third parameter (true means case-insensitive).
For example:
define('FOO', 'BAR', true);
echo FOO; // BAR
echo foo; // BAR
The above has introduced the difference between const and define when defining constants in PHP, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.