To create a constant in PHP, you can use the
define() function. The
define() function takes two arguments: the name of the constant and its value. The constant name must start with a letter or underscore, and can only contain alphanumeric characters and underscores. The value can be any data type, including strings, integers, floats, arrays, and objects.
Here is an example of how to define a constant in PHP:
define("SITE_NAME", "My Site");
You can then access the value of the constant using its name, like this:
echo SITE_NAME; // Outputs: "My Site"
You can also define constants using the
const keyword, like this:
const SITE_NAME = "My Site"; echo SITE_NAME; // Outputs: "My Site"
Note that constants defined using the
const keyword cannot be changed after they are defined. They are also case-sensitive, unlike constants defined using the
It is a good practice to define constants in all uppercase letters to distinguish them from variables. You can also use the
define() function to define constants with case-insensitive names by setting the third argument to
true. For example:
define("SITE_NAME", "My Site", true); echo site_name; // Outputs: "My Site"