PHP Constants
PHP Constants
In PHP Constants is a name/identifier for a simple value that cannot be changed during the script execution.
-
A constant does not use
$before its name. -
A constant’s value remains the same once defined.
-
Constants are global and can be accessed from anywhere in the script.
1. Define a Constant
PHP has two ways to define constants:
A) Using define()
Syntax:
B) Using const keyword
Used inside classes or global scope.
2. Difference Between define vs const
| Feature | define() |
const |
|---|---|---|
| Can be used inside conditions | ✔️ Yes | ❌ No |
| Can be used inside classes | Limited | ✔️ Yes |
| Supports expressions | ✔️ Yes | ❌ No |
| Case-insensitive names | ✔️ Yes (optional) | ❌ No |
| Set at runtime | ✔️ Yes | ❌ No, compile-time |
3. Case-Insensitive Constant
(Available only with define, not recommended in modern PHP)
4. Constant Arrays
You can define arrays as constants:
Using const:
5. Magic Constants (Predefined by PHP)
PHP provides many built-in constants that change depending on where they are use.
| Magic Constant | Description |
|---|---|
__LINE__ |
Current line number |
__FILE__ |
Full path and filename |
__DIR__ |
Directory of the file |
__FUNCTION__ |
Function name |
__CLASS__ |
Class name |
__TRAIT__ |
Trait name |
__METHOD__ |
Method name |
__NAMESPACE__ |
Current namespace |
Example:
6. Global Accessibility of Constants
Once defined, constants are automatically global — no need to use global keyword.
7. Check if Constant Exists
Summary
| Feature | Constant |
|---|---|
| Defined using | define() or const |
| Changeable? | ❌ No |
| Global? | ✔️ Yes |
Uses $? |
❌ No |
| Supports arrays? | ✔️ Yes |
| Magic Constants | FILE, LINE, etc. |
If you want, I can continue with the next topic:
👉 PHP Operators
👉 PHP If…Else Statements
👉 PHP Arrays
