What is the difference between a constant defined with define() and one defined with const?
Last updated
Both create constants, but const is a compile-time language construct defined at the top level or in classes, while define() is a runtime function that can be called conditionally and build names dynamically.
const:Resolved at compile time, so it can't be used inside conditionals or loops.
The only way to define class constants:
class A { const VERSION = 1; }.Name must be a literal identifier, not a computed string.
define():Runs at runtime, so you can call it inside
ifblocks or define the name from a variable.Was needed for case-insensitive constants (third argument, now removed in PHP 8).
Cannot define class constants.
Shared traits: Both create immutable values; check existence with
defined().
[lang:php]
const MAX = 100; // compile time, top level
define('MIN', 1); // runtime
if ($debug) {
define('LOG_LEVEL', 'verbose'); // conditional: const can't do this
}