PHP Constants
In PHP, constants are identifiers (names) for simple values. Once a constant is defined, it cannot be changed or undefined. Constants are useful for defining values that should remain consistent throughout your script.
Here’s a basic overview of how to work with constants in PHP:
Defining Constants
You use the define() function to create a constant. The define() function takes two parameters: the name of the constant and its value.
define('SITE_NAME', 'MyWebsite');
define('MAX_USERS', 100);
Accessing Constants
Constants are accessed directly by their name without the need for a $ sign.
echo SITE_NAME; // Outputs: MyWebsite
echo MAX_USERS; // Outputs: 100
Case Sensitivity
By default, constant names are case-sensitive. However, you can make them case-insensitive by setting the third parameter of define() to true.
define('DB_HOST', 'localhost', true); // Case-insensitive
echo DB_HOST; // Outputs: localhost
echo db_host; // Also outputs: localhost
Constants in Classes
In PHP 5.3.0 and later, you can also define constants within classes using the const keyword.
class MyClass {
const MY_CONST = 'SomeValue';
}
echo MyClass::MY_CONST; // Outputs: SomeValue
Magic Constants
PHP also provides a set of predefined "magic constants" that are automatically defined. These constants include:
__LINE__ - The current line number of the file.
__FILE__ - The full path and name of the file.
__DIR__ - The directory of the file.
__FUNCTION__ - The name of the function.
__CLASS__ - The name of the class.
__METHOD__ - The name of the class method.
__NAMESPACE__ - The name of the current namespace.
Example of Magic Constants
echo __FILE__; // Outputs the full path of the current file
echo __LINE__; // Outputs the current line number
Constants are a great way to make your code more readable and maintainable by providing meaningful names for values that should not change.