Constants
Variables offer a flexible way of storing data. You can change their values and the type of data they store at any time. However, if you want to work with a value that you want to remain unchanged throughout your script's execution, you can define and use a constant. You must use PHP's built-in define() function to create a constant, which subsequently cannot be changed. To use the define() function, you must place the name of the constant and the value you want to give it within parentheses, separated by a comma:
define("CONSTANT_NAME ", 42);
The value you want to set can be a number, a string, or a Boolean. By convention, the name of the constant should be in capital letters. Constants are accessed with the constant name only; no dollar symbol is required. Listing 4.4 shows you how to define and access a constant.
Listing 4.4 Defining and Accessing a Constant
1: <html>
2: <head>
3: <title>Listing 4.4 Defining and accessing a constant</title>
4: </head>
5: <body>
6: <?php
7: define("USER", "Gerald");
8: echo "Welcome ".USER;
9: ?>
10: </body>
11: </html>
![]() | When using constants, keep in mind they can be used anywhere in your scripts, including external functions which are included. |
Welcome Gerald
The define() function can also accept a third, Boolean argument that determines whether or not the constant name should be case-independent. By default, constants are case-dependent. However, by passing true to the define() function, we can change this behavior, so if we were to set up our USER constant as
define("USER", "Gerald", true);
we could access its value without worrying about case:
echo User;
echo usEr;
echo USER;
These expressions are all equivalent, and all would result in an output of Gerald. This feature can make scripts a little friendlier for other programmers who work with our code, as they will not need to consider case when accessing a constant that we have defined. On the other hand, given the fact that other constants are case-sensitive, this might make for more rather than less confusion as programmers forget which constants to treat in which way. Unless you have a compelling reason to do otherwise, the safest course is to keep your constants case-sensitive and define them using uppercase characters, which is an easy-to-remember convention.
Predefined Constants
PHP automatically provides some built-in constants for you. For example, the constant __FILE__ returns the name of the file that the PHP engine is currently reading. The constant __LINE__ returns the line number of the file. These constants are useful for generating error messages. You can also find out which version of PHP is interpreting the script with the PHP_VERSION constant. This can be useful if you need version information included in script output when sending a bug report.