PHP constant is a name or an identifier for a simple value which can’t change throughout the execution of the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Numbers and underscore is better to come after letters. Constants may have different types of values and they get determined by ‘define(‘name’, value) ‘ function. Another way is to determine them in ‘const name= value’ model since php 5.3 comes. The usage is to avoid repeating long values in your program.
Note: Unlike variables, constants are automatically global across the entire script. By default constant is case-sensitive. Constant identifiers are always uppercase.If you have defined a constant, it can never be changed or undefined.
Creating a PHP Constant:
To create a constant, use the define() function.
define(name, value, case-insensitive)
- name: Specifies the name of the constant
- value: Specifies the value of the constant
- case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
The example below creates a constant with a case-sensitive name:
echo pi; // Prints 3.141516
const R= 8.314;
echo R; // Prints 8.314
Constants can’t change along the program and they don’t have ‘$’ sign at the first. They are accessible just by names of them. If you use second method, you must use it at the top of your program but the first method has no restriction.
Some valid constant names
Invalid constant names
define("2TESTVALUE", "invalid ");
define("__TESTVALUE__", "invalid ");
Seven predefined constants are existing in PHP (they are categorized in magic methods). Some of them have usages which I will explain in detail, later. They all begin and end with two underscore. The three first are case insensitive. Let me illustrate them in example below:
Echo __Line__ // Prints Line Number this echo code is.
Echo __FILE__ // Prints this php file location.
Echo __dir__ // Prints this php directory location.
Echo __FUNCTION__ //Prints current function name
Echo __CLASS__ // Prints current class name.
Echo __METHOD__ // Prints current class method name.
Echo __NAMESPACE__ // Prints current name of namespace.