In a production level code it is very important to keep information as either variables or constants rather than using them explicitly. A PHP constant is nothing but an identifier for a simple value that tends not to change over time(such as the domain name of a website eg. www.geeksforgeeks.org). It is ideal to keep all the constants in a single PHP script so the maintenance is made easier. A valid constant name must start with an alphabet or underscore and requires no ‘$’. It is to be noted, constants are irrespective of their scope i.e constants are automatically of global scope.
In order to create a constant in PHP, we must use the define() method.
bool define(identifier, value, case-insensitivity)
Parameters: The function has two required parameters and one optional parameter.
- identifier: Specifies the name to be assigned to the constant.
- value: Specifies the value to be assigned to the constant.
- case-insensitivity(Optional): Specifies whether the constant identifier should be case-insensitive. By default it is set to false i.e. case-sensitive.
Return Type: This method returns TRUE on success and FALSE on Failure.
Below are some examples to illustrate working of define() function:
- Below program illustrates defining case-insensitive constants:
// case-insensitive costants
Hello Geeks! // Case Insensitive thus value is echoed Hello Geeks!
- Below program illustrates defining case-sensitive constants:
// case-sensitive constant
constant // Case Sensitive thus value not echoed Hello Geeks!
The PHP compiler will also throw a warning for above program along with the output as: “PHP Notice: Use of undefined constant constant- assumed ‘constant’ in line 5”.
- Constants are identifiers that can be assigned values(string, boolean, array, integer, float or NULL) which generally don’t change overtime.
- Constants are irrespective of scope and always populate the global scope.
- define() method is used to define constants.
- defined() method is used to check if a constant is defined.
- constant() method is used to return the value of a constant and NULL if not the constant is not defined.