Constants
If you find yourself setting a variable for convenience and never changing it during a script, chances are you should be using a constant. Constants are like variables except that once they are defined, they cannot be undefined or changed—they are constant, as the name suggests. Unlike many other languages, constants are not faster than variables in PHP. The primary advantage to using constants is the fact that they do not have a dollar sign at the front and, therefore, are visibly different from variables. Furthermore, constants are automatically global across your entire script, unlike variables.
To set a constant, use the define()
function. It takes two parameters: the first being the name of the constant to set, and the second being the value to set. For example, the following line of code sets the constant SecondsPerDay
, then prints it out:
define("SecondsPerDay", 86400); print SecondsPerDay;
Note that it is not $SecondsPerDay
or SECONDSPERDAY
—the names of constants, like the names of variables, are case-sensitive—but unlike variables, they do not start with a dollar sign. You can change this behavior by passing true as a third parameter to define()
, which makes the constant case-insensitive:
define("SecondsPerDay", 86400, true); print SecondsPerDay; print SECONDSperDAY;
There are two helpful functions available for working with constants, and these are defined()
and constant()
. The defined()
function is basically the constant equivalent of isset()
, as it returns
Get PHP in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.