Almost every good PHP application will be need to access some global values at some point. Constants are a programming pattern that you can access anywhere, at anytime and be sure that it won’t be overwritten. You will find this universal concept in almost every programming language. In this article, I will consolidate some great tips for working with constants in PHP and the specifics to keep an eye on.

It’s just a global variable right?

Nope. Variables change. Constants wouldn’t be very constant if they kept changing, would they? This is the most important aspect of a constant is that it cannot change once you have defined it. If you simply want a global variable that you can transform throughout your program, you do not want a constant. That being said, you can access a constant anywhere without regard to scope.

You will find that constants can be very helpful at the top of scripts/classes as default or configuration values. They do not take the overhead of other methods of accessing global variables and you don’t have to worry about them being changed elsewhere in your code.

Tips for Creating Constants

// Valid constant names
define("FOO",     "solid");
define("FOO2",    "solid state");
define("FOO_BAR", "solidlystated");
 
// Invalid constant names
define("2FOO",    "solid");
 
// Check for, then set a constant
defined("FOO") or define("FOO", "solid");

These examples are similar to those seen in the PHP manual website.

  • PHP constants are case-sensitive
  • By convention, use all uppercase characters
  • By convention, use underscores as spaces
  • Constant names can only start with letter or underscore
  • Numbers can be used after the first character
  • Constant name must be quoted when defined
  • Constant names cannot be reserved PHP keywords

Difference between a Constant and a Singleton

Singletons are a pattern of programming that most developers write with one hand, while shaking a fist at in the other hand. Singletons are frowned upon for various debatable reasons, but those are outside the scope of this article (pun intended).

Singletons get their name from the idea that they only exist as a single instance of a class, allowing you to reliably access them to manage consistent data. Some applications, especially larger ones, use a singleton class to manage data that could normally be handled with constants. Of course, there is a major difference- singletons are mutable at run-time.

A singleton is useful because it’s a globally accessible class (with variables and methods) that, when done right, only allows one instance to be created.

Global Constants Versus Class Constants

Class constants also exist in PHP, giving you the immutable power of a constant with the scope of a class. Instead of using define(), you simply assign a class constant with the keyword const.

Solid Tip: Until PHP 5.3, const could not be used in the global scope and had to be used in a class.

As of PHP 5.3, you CAN use const globally, and it will work fine, but your IDE will insist that it is an error (As of this article Dreamweaver CS5 still thinks this is an error outside a class). Don’t defy convention. Use define() for your global constants and, if you must, use const inside classes. You can access class constants in the following manner:

// inside your class
class MyFOO
{
    const FOO = 'solid';
 
    function somefunc()
    {
        echo self::FOO;
    }
}
 
//outside your class
$myfoo = new MyFOO();
echo $myfoo::FOO;
 
// Note that FOO could be defined as a global also

Const is a language construct and not a method, having many other minor differences compared to define(), such as the values it can be assigned. Most notably, it cannot be assigned inside a conditional block.

// Invalid before PHP 5.3 outside of a class
const FOO = 1;
 
// Invalid EVERYWHERE
const FOO = 1+1;
 
// Invalid EVERYWHERE also
if(...){ const FOO = 1; }

Tips for Retrieving Constants

It is good habit to use defined() along with define() (as seen in the final example below). If you have already defined a constant, PHP will throw a Notice. You could also wrap other conditionals around define() to suit your needs.

The bullet points up top remind you that constant names must be quoted when being defined. Don’t get confused when trying to echo the constant back to the screen, though. If you put a constant inside a quote, then its just an uppercase word in quote (maybe someone is shouting).

defined('FOO') or define('FOO', 'solid');
 
echo "FOO state"; // echoes FOO state
echo 'FOO state'; // echoes FOO state
echo FOO." state"; // echoes solid state

Hopefully, these tips and examples have helped you decide whether constants are what you are looking for, or cleared up any confusion about a couple of the alternatives. Got a question or concern about something I did or didn’t cover? Let me know with a comment below.