PHP constants is an identifier (name) for a simple value.
As the name suggests, that value cannot change during the execution of the script.
Rules for constants
- The rules for naming constant name is same as rules for naming variable names.
- $ sign is not used with constants.
- Constants are case-sensitive.
- A constant name must start with letter(a-z or A-Z) or underscore(_) followed by any number of letters, numbers or underscores.
- Constant name cannot start with numbers.
- The scope of constant is global means you can access constants anywhere in script.
Syntax to create php constant:
Following is a general syntax to create constant:
1 2 3 |
define("constant_name", "constant_value") OR define("constant_name", "constant_value", true) |
define() – It is a function use to define constant.
constant_name – For convention constant_name are always uppercase.
constant_value – must to specifies.
true/false specifies whether the constant name should be case-insensitive.
If you do not mention anything then it is by default false.
Example:
1 2 3 4 5 6 7 8 9 |
<?php define("STR1", "Hello world"); //valid define("STR12", "Hello world again"); //valid define("STR_12", "Hello world ones more"); //valid define("12str", "Hello world"); //invalid ?> |
Constants are case-sensitive.
Let’s see following two examples to understand,
1 2 3 4 5 |
<?php define("GREETINGS", "Hello World!", True); echo GREETINGS; echo greetings; ?> |
Output
1 |
Hello World!Hello World! |
Difference between variables and constants
- To create variable, you have to use doller($) sign before variable name.
But there is no need to write a dollar sign ($) before a constant - Variables have there scoping rules, local, global, static.
Constants accessed anywhere in script without regard to scoping rules. - You can change value of variable at anywhere in program.
But Constants can not be redefined. - Value of variable is simply assign using assignment operator(=).
Constants cannot be defined by simple assignment, they defined using the define() function.