6. Constants: Defining Fixed Values
Constants are identifiers for simple values that cannot be changed during the script's execution. Unlike variables, constants do not start with a dollar sign.
Defining Constants
We use the built-in define() function to create a constant. By convention, constant names are typically written in uppercase.
php
User limit: " . MAX_USERS; // Attempting to redefine a constant results in an error // define("SITE_NAME", "New Site"); // Fatal error ?>Class Constants (Introduced in OOP)
Constants can also be defined inside classes using the const keyword.
Magic Constants
PHP provides several predefined constants, called 'Magic Constants', which change based on where they are used. They are case-insensitive.
| Constant | Description |
|---|---|
__LINE__ | The current line number of the file. |
__FILE__ | The full path and filename of the file. |
__DIR__ | The directory of the file. |
__FUNCTION__ | The function name. |
php
The file path is: " . __FILE__; ?>