A constant in PHP is a value that cannot be changed during the execution of a script. Once a constant is defined, its value remains the same throughout the script, and it cannot be redefined or undefined.
Constants are useful for defining values that are frequently used in a script, such as configuration settings or mathematical constants. Defining constants also helps make code more readable and maintainable by giving meaningful names to values that would otherwise be hard-coded.
In PHP, you can define a constant using the define()
function. Here’s an example:
define("PI", 3.14159);
In this example, the define()
function defines a constant named “PI” with a value of 3.14159. Once defined, the value of PI cannot be changed during the execution of the script.
You can also define constants with arrays:
define("FRUITS", ['apple', 'banana', 'orange']);
In this example, the define()
function defines a constant named “FRUITS” with an array of fruits as its value.
To access a constant, you can simply use its name:
echo PI; // output: 3.14159
echo FRUITS[0]; // output: apple