PHP Constants. Besides variables in PHP, you can also store data in constants. Constants are similar to variables but their value can not be changed.
When we have to store a value in our program on a memory location, which can not be changed during the entire program, then we define the Constant Identifier to store such values.
define() function is used for PHP constants.
Sometimes you need to store such data that can not be changed. For example, you are performing geometric operations in which the value of PI is required. The value of PI always remains 3.14.
If you store the value of PI through the variable, then it is possible that by mistake or by any operation, it will change its value. If this happens then all operations will produce wrong results.
In this situation, PI can be define as constant. By doing so, the value of PI can not be changed in any way during the program run.
PHP Constants Syntax
Define function is used to define constants in PHP. Its simple syntax is being given below.
Commonly the stringName we specify as Constant, that name is Case Sensitive, but if we do not want to keep that name Case Sensitive, then we have to specify False Keyword as the third argument.
To define constance, 3 arguments are passed in the define function.
- constant-name – this is the name of constant. It should be unique in the name program.
- constant-value – This is the value of constant.
- case-sensitive (optional) – This is the Boolean (TRUE, FALSE) value. This is an optional argument without it can also be created constant. If you want a constant non case sensitive then you pass it to the value true, otherwise its value by default is false.
While using Constants in the program, one thing you should always keep in mind is that constants are define and not used with dollar ($).
<!DOCTYPE html> <html> <head> <title>PHP Constants</title> </head> <body> <?php define("PI",3.14); echo "PI Value is:".PI; ?> </body> </html>
PI Value is: 3.14