As like as many programming languages, PHP also contains constants. It has some predefined constants in its core like PHP_VERSION, PHP_DEBUG and more. We can define constants by using the define() function.
Generally, constants are in global scope. We can also define class-specific or interface-specific constants by using PHP const keyword. In this tutorial, we are going to see examples for defining and accessing constants.
PHP constants are case sensitive by default. We can enable case insensitivity while defining constants. Conventionally, constants should have uppercase letters and should start with the underscore ( _ ) or a letter.
In a previous tutorial, we have seen about PHP variable which is completely differed from constants. PHP contains some special constants named as magic constants.
These magic constants are not actually constants because of revealing with different values based on the place they are used. The magic constants are case-insensitive.
This code defines PI constant and prints it to the browser using PHP echo statement.
define("PI",3.14); echo PI; // Output: 3.14
In the above program, the constant is defined as a key-value pair. The key is used to get the value of the constant.
In the above program, the define() function gets only two parameters. The define() has an optional third parameter to set the case insensitivity of a constant. By default, the constants are case sensitive.
We can make them case insensitive by setting the case insensitivity flag to true. So, the above example code can be changed as,
define("PI",3.14, true); echo pi; // Output: 3.14
PHP const is a language construct where the define() is a function. We should use static name and value with the const statement to initialize constants where the define() function allows variable interpolation and function call while defining constant. Constants defined using this construct is always case sensitive.
Defining constants using the const statement is good in readability aspect, though the define() has many features by enabling case insensitivity, allowing function call assigning values to the constant, revealing constants at runtime.
The following line shows the example of initializing constants using a const statement.
const PI = "3.14"; echo PI; // Output: 3.14
PHP constant() function is used to get the value of the constant by sending its id as an argument of this function. The following example code uses constant() function to get the constant value by using the id.
define("PI",3.14); define("USERTYPE","GUEST"); $id = "PI"; echo constant($constant);
The get_defined_constants() function will dump all user-defined constants and core constants into an array by default. It receives a boolean value as its argument to categorize the constants.
If it is set to true, then this function will categorize all built-in constants and user-defined constants with a multidimensional array.