- PHP constants are identifier or name that can’t be changed during the execution of the script except for magic constants, which are not really constants.
- Constants can never be undefined or changed, they are similar to the variable except once defined.
- PHP constants follow the same PHP variable rules and it remains constant across the entire program.
- Conventionally, in uppercase letters PHP constants should be defined and it can be started with an underscore or letter only.
- PHP constants consists of two types, they are:
- Using define () function
- Using const keyword
Using define () function
- In PHP use the define () function to create a constant and it defines constant at run time.
- In this function name specifies the constant name, value specifies the constant value and case-insensitive specifies whether a constant is case-insensitive.
- By default, if value is false it means it is case sensitive.
Sample Code
[pastacode lang=”php” manual=”%3C%3Fphp%20%20%20%20%0Adefine(%22MESSAGE%22%2C%22Welcome%20to%20Wikitechy%22%2Ctrue)%3B%2F%2Fnot%20case%20sensitive%20%20%20%20%0Aecho%20MESSAGE%2C%20%22%3C%2Fbr%3E%22%3B%20%20%20%20%0Aecho%20message%3B%20%20%20%20%0A%3F%3E%20%20%20%20%0A” message=”” highlight=”” provider=”manual”/]
Output

Using const Keyword
- PHP introduces a const keyword to create a constant and it defines constants at compile time.
- It constructs a language, not a function.
- The constant defined using const keyword are case-sensitive.
Sample Code
[pastacode lang=”php” manual=”%3C%3Fphp%20%20%20%20%20%20%0A%20%20%20%20define(%22MSG%22%2C%20%22Wikitechy%22)%3B%20%20%0A%20%20%20%20echo%20MSG%2C%20%22%3C%2Fbr%3E%22%3B%20%20%0A%20%20%20%20echo%20constant(%22MSG%22)%3B%20%20%0A%20%20%20%20%2F%2Fboth%20are%20similar%20%20%0A%3F%3E%20%20%0A” message=”” highlight=”” provider=”manual”/]
Output
