PHP Constants
A 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 underscores are better to come after letters. Constants may have different types of values and they are determined by the ‘define (‘name’, value)’ function. Another way is to determine them in the ‘const name= value’ model since PHP 5.3 came. The purpose is to avoid repeating long values in your program.
Note: Unlike variables, constants are automatically global across the entire script. By default, the 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.
Syntax
Parameters:
- 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:
<?php
define('pi', 3.141516);
echo pi; // Prints 3.141516
const R= 8.314;
echo R; // Prints 8.314
?>
Constants can’t change during the program and they don’t have a ‘$’ sign at the beginning. They are accessible just by the names of them. If you use the second method, you must use it at the top of your program, but the first method has no restrictions.
Some valid constant names
define("TESTVALUE", "valid"); define("TESTVALUE2", "valid"); define("TESTVALUE_3", "valid");
Invalid constant names
define("2TESTVALUE", "invalid "); define("__TESTVALUE__", "invalid ");
Seven predefined constants exist in PHP (they are categorized as magic methods). Some of them have usages which I will explain in detail later. They all begin and end with two underscores. The three first are case insensitive. Let me illustrate this with the example below:
<?php
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.
?>