Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Compare define() vs const in PHP
In PHP, both define() and const are used to declare constants, but they have important differences in when and how they can be used.
Syntax
<?php
const VAR = 'FOO';
define('VAR2', 'BAR');
echo VAR . "<br>";
echo VAR2;
?>
FOO BAR
Key Differences
Compile-time vs Runtime Definition
The basic difference is that const defines constants at compile time, whereas define() defines them at run time ?
<?php
// This works - const is defined at compile time
const COMPILE_TIME = 'Available immediately';
// This also works - define() at runtime
define('RUNTIME', 'Available after execution');
echo COMPILE_TIME . "<br>";
echo RUNTIME;
?>
Available immediately Available after execution
Conditional Definition
We can't use const in conditional blocks, while define() allows conditional constant declaration ?
<?php
$condition = true;
if ($condition) {
// const VAR = 'FOO'; // This would cause a syntax error
define('CONDITIONAL_CONST', 'This works');
}
echo CONDITIONAL_CONST;
?>
This works
Value Types
const accepts only static scalars (strings, numbers, booleans, null), whereas define() accepts any expression ?
<?php
// const with static values
const STATIC_VALUE = 'Hello';
const NUMBER_VALUE = 42;
// define() can use expressions
define('EXPRESSION_VALUE', 'Hello ' . 'World');
define('CALCULATED', 10 * 5);
echo STATIC_VALUE . "<br>";
echo EXPRESSION_VALUE . "<br>";
echo CALCULATED;
?>
Hello Hello World 50
Case Sensitivity
const is always case-sensitive, while define() can optionally be case-insensitive ?
<?php
const CASE_SENSITIVE = 'Always case sensitive';
define('CASE_INSENSITIVE', 'Can be case insensitive', true);
echo CASE_SENSITIVE . "<br>";
echo case_insensitive; // Works due to third parameter being true
?>
Always case sensitive Can be case insensitive
Class Constants
const can be used inside classes to declare class constants, but define() cannot ?
<?php
class MyClass {
const CLASS_CONSTANT = 'Valid class constant';
// define('INVALID', 'value'); // This would cause an error
public function showConstant() {
return self::CLASS_CONSTANT;
}
}
echo MyClass::CLASS_CONSTANT . "<br>";
$obj = new MyClass();
echo $obj->showConstant();
?>
Valid class constant Valid class constant
Comparison Summary
| Feature | const | define() |
|---|---|---|
| Definition Time | Compile-time | Runtime |
| Conditional Use | Not allowed | Allowed |
| Value Types | Static scalars only | Any expression |
| Case Sensitivity | Always case-sensitive | Configurable |
| Class Constants | Supported | Not supported |
Conclusion
Use const for simple, static constants and class constants. Use define() when you need conditional definition, expressions, or case-insensitive constants.
