Constants are similar to variables. Constants are given names, and values are stored in them. However, constants are constant; they can’t be changed by the script. After you set the value for a constant, it stays the same. If you use a constant for weather and set it to sunny, it can’t be changed.
Constants are set by using the define statement. The general format is as follows:
define(“constantname”,”constantvalue”);
For example, to set a constant with the weather, use the following statement:
define(“WEATHER”,”Sunny”);
This statement creates a constant called WEATHER and sets its value to “Sunny”.
When naming constants, use descriptive names, as you do for variables.
However, unlike variables, constant names do not begin with a dollar sign ($).
By convention, constants are given names that are all uppercase so you can see easily that they’re constants. However, PHP accepts lowercase letters without complaint.
You can store either a string or a number in a constant. The following statement, which defines a constant named INTEREST and assigns to it the value .01, is perfectly okay with PHP:
define (“INTEREST”,.01);
Constants should not be given names that are keywords for PHP. Keywords are words that have meaning for PHP, such as echo, and they can’t be used as constants because PHP treats them as the PHP feature of the same name. PHP will let you define a constant ECHO without giving an error message, but it will have a problem when you try to use the constant. For example, if you use the following statement:
echo ECHO;
echo ECHO;
PHP gets confused and displays an error message. It sees the constant as the beginning of another echo statement, but it can’t find all the things it needs to complete the first echo statement.
Some PHP keywords include the following:
and, as, break, case, class, const, continue, declare, default, die, do, echo, else, empty, eval, exit, for, foreach, function, global, if, include
0 comments:
Post a Comment