The Building Blocks: Data Types, Literals, Variables, and Constants - Part 3
[next]
The Building Blocks:
Data Types, Literals, Variables, and Constants - Part 3
Constants
"The only thing constant in life is change."
—Francois de la Rouchefoucauld, French classical author
Some real-world constants, such as pi, the speed of light, the number of inches in a foot, and the value of midnight, are values that don't change. PHP not only provides its own predefined constants but lets you create your own. Using constants makes it easy to write and maintain your programs.
What Is a Constant?
Unlike variables, a constant is a value that, once set, cannot be changed or unset during the execution of your script. An example of a constant is the value of pi or the version of PHP you are using. Constants are very useful because they are visible throughout a program (global in scope) and their values don't change; for example, a constant might be defined for the document root of your server, the name of your site, or the title, author, and copyright year of this book. Once defined, those values are fixed.
You can define constants at the top of your program or in another file that can be included in your script. (See the require()
and include()
functions discussed in "Managing Content with Include Files" on page 487.) Later if a constant value needs to be modified, once you change its value in the program, then when the program is executed, the new value will be reflected wherever the constant is used throughout the program, thus facilitating program maintenance.
Creating Constants with the define() Function
PHP constants are defined as words, and by convention, capitalized. Like variables, they are case sensitive and consist of uppercase and lowercase letters, numbers, and the underscore. Like variables, they cannot start with a number.
Unlike variables, constants are not preceded by a dollar sign and are not interpreted when placed within quotes. Constants are global in scope, meaning they are available for use anywhere in a PHP script.
The only way that you can create a constant is with he PHP built-in define()
function. Only a single, scalar value can be assigned to a constant, including strings, integers, floats, and booleans.
The define()
function creates a named constant. The first argument is the name of the constant and the second argument is the value that will be assigned to it. Constants are normally case sensitive, but you can use an optional third argument of TRUE
to turn off case sensitivity.
Format
Example 4.25
Explanation
|
The defined()
function checks whether a constant has been set. It returns TRUE
if the constant has been defined; otherwise, FALSE
.
[next]
URL: