In this tutorial you will learn about the PHP Constants and its application with practical example.
A constants is used for defining immutable values.Constant’s value cannot be modified during the execution of script.Constant name starts with a letter or underscore (dollar($) sign is not required before the name) and by convention constant names are always uppercase.
Constants are defined by using the define() function and its value can be accessed simply specifying its name.You can also use the function constant() to read a constant’s value.
Example:
1 2 3 4 5 6 7 8 |
<?php define("SIZE1", 15); echo SIZE1; echo constant("SIZE1"); // same as the previous statement ?> |
Constants v/s Variables:
- No need to write a dollar sign ($) before a constant name.
- May not be redefined or undefined after defining it.
- Constants cannot be defined by assignment statement, they can be only defined using the define() function.
- Can be accessed globally