Like other programming languages, PHP allows to define constants using define() function. Once a constant is defined, we can not change or revert it. We should store a value as constant which is never ever needed to be changed. For example, the value of pi can be defined as a constant as shown in the below code.
define("PI",3.14); echo PI; // Output: 3.14
In the above program, id of the constant is indicated with uppercase letters, which is the convention in defining constants. And, PHP constants are case sensitive. That is, if we use pi instead PI for a PHP print statement, then both wont display the same result.
We can define constants with an alternative way by using const keyword. But, this will work in PHP version 5.3.0 and greater. Before that, the const keyword is used to define PHP constants, only inside classes.
Once the constants are defined, then we can use it anywhere in the program. That means, PHP constants are coming under global scope. So we can use them inside the scope of the functions without using global keyword or anything like PHP global array $_GLOBALS.
We can use the id of constant as it is, to access them. And we can also use constant() function of PHP, to get the value of constant when its id is not obviously known. For example,
define("PI",3.14); define("USERTYPE","GUEST"); $constant = $_POST["constantName"]; echo constant($constant);
Let us consider the name of the constant is going to be taken from user. Here, $_POST[“constantName”] is used to grab user’s input and stored into a variable. If we as the user enter ‘PI’, then the value 3.14 will be displayed to the browser.
We can dump all the defined constants into an array using get_defined_constants() function. If we pass the Boolean value true as an argument, then this function will return array of entire PHP core constants, PCRE extension constants and also the user defined constants. Otherwise, it will return only the core constants of PHP like E_ERROR, E_WARNING and etc.
PHP have some special in-built constants which are varied from the usual constants we discussed above. Some of the example of predefined constants are __LINE__, __FILE__, __CLASS__ and etc. These magical constants are varied from the usual PHP constant by the following points of view.
This PHP code tutorial was published on April 26, 2013.