If you find yourself setting a variable for convenience and never changing it during a script, the chances are you should be using a constant instead. Constants are like variables except that once they are defined they cannot be undefined or changed - they are constant as the name suggests. In many languages, constants are faster than variables and so are recommended, but this is not the case as much in PHP - although they are perhaps a small amount faster, the primary advantage to using constants is the fact that they do not have a dollar sign at the front, and so 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, with the first being the name of the constant to set, and the second being the value to which you wish to set it. For example, this following line of code sets the variable CURRENT_TIME to be the return value of the time() function, then prints it out:

define("CURRENT_TIME", time());

Note that it is not $CURRENT_TIME or Current_Time - constants, like variables, are case sensitive, but unlike variables they do not start with a dollar sign. You can change this behaviour by passing true as a third parameter to define(), which makes the constant case-insensitive:

define("CURRENT_TIME", time(), true);
print Current_TiMe;

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 true if the constant string you pass to it has been defined. For example:

define("CURRENT_TIME", time(), true);
if (defined("CURRENT_time")) {
    /// etc }

Note that you should pass the constant name into defined() inside quotes.

Finally, constant() is a function that might seem redundant at first, but it makes sense if you give it a chance: it returns the value of a constant. Now, I realise that you can just get the value of a constant by using it directly, e.g. "print MY_CONSTANT;", but how would you accomplish that if you did not know the constant's name? If you were working with a variable, you could use a variable variable, but this is not possible with constants - hence the constant() function.

    define("Current_Time", time(), true);
    $somevar = "CURRENT_TIME";
    print constant($somevar);


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Pre-set constants >>

Previous chapter: References

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.