What is the Difference Between define() and const Keyword in PHP ?
Syntax
// Using define() function
define("CONSTANT_NAME", value);
// Using const keyword (outside of class)
const CONSTANT_NAME = value;
Important Points
- Constants defined using
define( )
are global and can be defined anywhere in the script, including within functions or conditionals. - Constants defined using
const
Keywords are class constants and can only be defined within classes or interfaces. A define()
method is evaluated at runtime, whereasconst
the keyword is evaluated at compile time.- Constants defined using
const
keywords are case-sensitive, whereas those defined usingdefine()
are case-insensitive by default.
Difference between define() and const
define() | const keyword |
---|---|
Defines constants at runtime | Defines class constants at compile time |
Can be defined anywhere in the script | Can only be defined within classes or interfaces |
Case-insensitive by default | Case-sensitive by default |
Global scope | Class scope |
Usage
- Dynamic vs. Static Definition:
define()
allows dynamic definition of constants at runtime, whileconst
keyword allows static definition within class or interface definitions. - Scope: Constants defined using
define()
are global and can be accessed from anywhere in the script, while constants defined usingconst
keyword are scoped to the class or interface in which they are defined. - Case Sensitivity: Constants defined using
const
keyword are case-sensitive by default, whereas those defined usingdefine()
are case-insensitive unless explicitly specified.
Example:
// Using define() to define a Global constant
define("PI", 3.14);
// Using const keyword to define a Class constant
class Math {
const PI = 3.14;
}
Contact Us