A constant is an identifier for any value. As the also says, that the value can’t be changed during program execution. A constant is case-sensitive by default and by convention, a constant identifiers are always uppercase. A valid constant name should start with a letter or underscore, followed by any number of letters, numbers, or underscores. Any constants name can be used anywhere in the program if needs to print the same values on various parts of the program. As a PHP constant may contain a long string value so we don’t need to write same string values again and again. You just define the constant and call it whenever you need to print the value.
How to define a PHP Constants with constant() function
To define a constant in PHP you need to use the define() function and if you want to print the value of the constant, you just need to specify the constant name only and this will print the value autometically.
// Valid constant names
define("MYCONST2", "something else");
define("MYCONST_12", "something more");
// Invalid constant names
// This is valid, but should be avoided:
// PHP may one day provide a magical constant
// that will break your script
What are the main differences between constants and variables in PHP
- There is no need to use a dollar sign ($) before any constant, instead a variable name starts with a dollar sign.
- Constants will be defined using the define() function instead for a variable we use (=) operator to assign the value.
- Constants values can not be chaned anywhere in the program. Once you define the program it will display the same value instead for a variable, a new value can be assigned anywhere in the program.
Magic constants in PHP
PHP provides a large number of predefined constants with the default values which are called Magic constants. The Magic constants are case-insensitive.
Following are the PHP Magic constants
The current line number of the file.
The full path and filename of the file with symlinks resolved.
The directory of the file.
The function name.
The class name.
The trait name.
The class method name.
The name of the current namespace.