PHP Constants

Like other programming languages, PHP allows defining constants using the define() function. Once a constant is defined, we can not change or revert it. We should store a value as a 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.

echo PI; // Output: 3.14

In the above program, the 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 won’t 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.


Scope of Constants

Once the constants are defined, then we can use it anywhere in the program. That means PHP constants are coming under the global scope. So we can use them inside the scope of the functions without using the global keyword or anything like PHP global array $_GLOBALS[].

Accessing Constants

We can use the id of a constant as it is, to access them. And we can also use the constant() function of PHP, to get the value of constant when its id is not obviously known. For example,

$constant = $_POST["constantName"];
echo constant($constant);

Let us consider the name of the constant is going to be taken from the 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 in 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 an 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.

Magical Constants

PHP have some special inbuilt constants which are varied from the usual constants we discussed above. Some of the examples 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.

  • PHP magical constants are case sensitive, unlike other constants.
  • We can expect the result of this constant to return values based on the location they are used in the program.

This PHP code tutorial was published on April 26, 2013.

↑ Back to Top