What are the different ways to set PHP Constants

Zyxware default image1

A constant is a name for a simple value, which will not change at the time of execution. The main advantages are ranges from setting configuration values to saving integer values to be checked as strings (like status codes). PHP provides functions for constant values, which make the usage more easier. These functions are important in Drupal too, since we may need those when working in Drupal projects.

A name of constant follows the same rule as a label, it can start with a letter or underscore and can contain any number of letters or numbers. A PHP built-in name can also be used as a constant name, which is completely legal in PHP (For eg:"echo").

To define a constant we can use the "define" function or you can use the "const" keyword to define a constant outside a function definition. Once a constant is defined, it's value can never be changed or be undefined.

Using define function,

  define("CONSTANT_NAME", "constant value");

There is a third parameter to the define function, which is "case_insensitive"(boolean). If it is set, then the constant name will be considered case insensitive. By default it is case sensitive(ie: ABC, abc and Abc are 3 different constants).

  define("CONSTANT_NAME", "constant value", true); // constant_name and CONSTANT_NAME are same.

We can define a constant in a names pace using the define() function. By default it is added to the global name space. But if we need to add the constant to a particular name spce, since that will be more easier for managing them later on. To add a constant to a name space we only need to specify the names pace before the constant name.

    namespace abc;
    define(__NAMESPACE__ . '\def', 'Good bye');

This will define a constant named "def" in the namespace abc.

Some constant related functions

  1. constant()

    This function will return the value of a constant specified. This is useful if we doesn't know the constant name at the current contest. Which will be a case when is stored in a variable or returned from a function.

  2. defined()

    This function will return TRUE if a particular constant is defined and FALSE unless. This is very useful in checking if a constant is defined or not.

  3. get_defined_constants()

    This function returns the names of all the constants defined till that moment. This will be very helpfull when we are debugging something related to constants. This function has a parameter "categorize"(boolean), which will return a categorized array of constants.

          eg: get_defined_constants(true);