Constant
The define() function defines a constant.
Constants are much like variables,
except for the following differences:
A constant's value cannot be changed after it is set
Constant names do not need a leading dollar sign ($)
Constants can be accessed regardless of scope
Constant values can only be strings and numbers
Syntax
define(name,value,case_insensitive)
Ex 1 :
Ex 2 :
Ex 3 :
Ex 4 :
Ex 5 :
Note :
The PHP constant is very similar to a PHP variable in that it is used to store a value but, unlike a variable, the value cannot be changed. It is called a constant because; you guessed it, it stays constant throughout the PHP program. By using a constant you "lock in" the value which prevents you from accidentally changing it.
Secondly, if you want to run a program several times using a different value each time, you do not need to search throughout the entire program and change the value at each instance. You only need to change it at the beginning of the program where you set the initial value for the constant.
Let's take a look at an example where we use the define function to set the initial value of a constant to the state in the US that a business is located in. Then we can use this constant in an accounting program.
define("STATE", "Ohio");
echo STATE;
In the example above, the define function begins with the function name define followed by parenthesis. Within the parenthesis are the name of the constant and the value to be assigned to the constant. Both are enclosed within quotation marks and separated by a comma. This is all followed by a semicolon.
You will notice that the value of Ohio is placed within quotation marks. This is because it is a character string. To store a numeric value you do not need quotation marks.
define("TAX", 4);
You will also notice that, unlike PHP variables, there is no $ in front of the constant name.
Although it is not required, most programmers use all uppercase letters when naming constants to make them stand out from the variables in their program.
You do not use quotation marks when you use a constant in an echo statement. If you do, the echo statement will display the constant name.
echo STATE; // will display Ohio
echo "STATE"; // will display STATE
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment