O'Reilly logo

PHP in a Nutshell by Paul Hudson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required