PHP Defining Constants
In a production-level code, it is very important to keep the 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 that 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 automatic of global scope. In order to create a constant in PHP, we must use the define() method.
Syntax:
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.
Note: From PHP 8.0, the constants defined with the help of the define() function may be case-insensitive.
Below are some examples to illustrate the working of the define() function in PHP.
Example 1: Below program illustrates defining case-insensitive constants.
PHP
<?php // Case-insensitive constants define( "Constant" , "Hello Geeks!" ,TRUE); echo constant; echo Constant; ?> |
Output:
Hello Geeks! // Case Insensitive thus value is echoed Hello Geeks!
Example 2: Below program illustrates defining case-sensitive constants.
PHP
<?php // Case-sensitive constant define( "Constant" , "Hello Geeks!" ); echo constant; echo Constant; ?> |
Output:
constant // Case Sensitive thus value not echoed Hello Geeks!
The PHP compiler will also throw a warning for the above program along with the output as “PHP Notice: Use of undefined constant constant- assumed ‘constant’ in line 5”.
Summary:
- Constants are identifiers that can be assigned values(string, boolean, array, integer, float, or NULL) that generally don’t change over time.
- Constants are irrespective of the scope and always populate the global scope.
- define() method is used to define constants.
- The defined() method is used to check if a constant is defined.
- The constant() method is used to return the value of a constant and NULL if not the constant is not defined.