In PHP, constants are like variables, but their values cannot be changed after they are defined. They are used to store values that remain constant throughout the execution of a script. Constants are typically used for values that are not supposed to change, such as configuration settings, fixed values, or other data that remains consistent.
Here's how you define and use constants in PHP:
1. Defining Constants:
Constants are defined using the `define()` function. They are usually named using uppercase letters and underscores.
php
define("PI", 3.14159);
define("MAX_USERS", 100);
2. Using Constants:
Once defined, constants can be used throughout your script. They don't require a dollar sign (`$`) before their names.
php
echo "The value of PI is " . PI; // Output: The value of PI is 3.14159
echo "Maximum users allowed: " . MAX_USERS; // Output: Maximum users allowed: 100
3. Built-in Constants:
PHP also provides several built-in constants that offer useful information, such as file paths, PHP versions, and system details. These constants are predefined and can be used directly.
php
echo "PHP version: " . PHP_VERSION;
echo "Current line number: " . __LINE__;
echo "Current file path: " . __FILE__;
4. Case Sensitivity:
By default, constants are case-sensitive. However, it's a good practice to define constants in uppercase to avoid confusion.
php
define("MY_CONSTANT", "Hello");
echo MY_CONSTANT; // Output: Hello
echo my_constant; // No output (Notice: Use of undefined constant my_constant)
5. Scope of Constants:
Constants are global by default and can be accessed from anywhere in your script, including within functions and classes.
php
define("CONFIG_VALUE", "123");
function showConfig() {
echo "Config value: " . CONFIG_VALUE;
}
showConfig(); // Output: Config value: 123
6. Magic Constants:
PHP provides a set of special constants known as "magic constants," which change based on their context. Examples include `__LINE__`, `__FILE__`, `__DIR__`, `__FUNCTION__`, and more.
Constants are useful for improving code readability, avoiding hard-coded values, and making it easier to manage configuration settings across your scripts.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc