Create a PHP Constant
o create a PHP constant, you can use the define()
function. The define()
function takes two arguments: the name of the constant and its value. The name of the constant must be a string, and the value can be of any type, including strings, integers, floats, and boolean values.
Here is an example of how to create a PHP constant:
define('PI', 3.14);
In this example, we create a constant called PI
with a value of 3.14
.
You can also use the const
keyword to define a constant in PHP. The syntax for using the const
keyword is similar to that of the define()
function, but with some differences. For example, you do not need to use quotation marks around the constant name when using the const
keyword.
Here is an example of how to create a PHP constant using the const
keyword:
const PI = 3.14;
Once you have defined a constant, you can use it like a normal variable, but you cannot change its value. If you try to reassign a value to a constant, you will get an error.
echo PI; // Outputs: 3.14
// This will produce an error
PI = 3.14159;
You can also use the defined()
function to check if a constant has been defined. The defined()
function returns a boolean value indicating whether or not the constant has been defined.
if (defined('PI')) {
echo "The constant PI has been defined.";
} else {
echo "The constant PI has not been defined.";
}