IT.COM

Defining your World: All About Constants

Spaceship Spaceship
Watch
Impact
4
I still remember the time I was a PHP beginner, these little constant things were always a source of confusion. I remember attempting to overwrite their values like you do with variables and being presented with an unfriendly error. What on earth could their use be?

Funnily enough, I now use constants all the time. In PHP4 constants could be defined one way, and one way only:

PHP:
define('MY_CONSTANT', 'TalkPHP.com');

However, since the much anticipated arrival of PHP5, we now have another way to define them directly inside our classes - the same place you would initiate member variables:

PHP:
const MY_CONSTANT = 'TalkPHP.com';

Notice how there are no quotes around the constant in this example. These are called class constants. In the previous example of defining a global constant, you must place quotes around the define. Failure to do so will give you another one of those pretty PHP notices. Very much unwelcome!

We're Not Just For Show

Constants don't just sit their looking luscious in amongst your code like a daffodil in the grass. Like a daffodil, constants do have purpose.

When you initiate a variable, that variable is not global unless you specify so using either $GLOBALS or the global construct. The good thing is that constants defined using the former example are global no matter what. That is:

PHP:
define('I_AM', 'Global!');

Whilst the latter example is only global to the class it was defined in. Constants do have their protocol though. Thankfully most of it is common-sense once you understand what you can or can't do with variables.

  • Constants cannot have spaces:
PHP:
define('my Constant', 'TalkPHP.com'); // won't work
  • Constants cannot begin with an integer:
PHP:
define('123myConstant', 'TalkPHP.com'); // won't work
  • Constants should be uppercase although either case will work:
PHP:
define('myconstant', 'TalkPHP.com'); // will work
define('MYCONSTANT', 'TalkPHP.com'); // preferred method
  • Constants may contain limited special charaters, such as the underscore but not the exclamation mark:
PHP:
define('MY_CONSTANT', 'TalkPHP.com'); // will work
define('MY_CONSTANT!', 'TalkPHP.com'); // won't work
  • Constants can only be defined using define() or const. You cannot simply assign:
PHP:
MY_CONSTANT = 'TalkPHP.com' // won't work
  • Constants cannot contain resources as their values, only string, integer, boolean and float are accepted. More specifically though they cannot even contain variables, class members or results of a mathematical call.
PHP:
const MY_CONSTANT = sqrt(7); // won't work

Another plus point about constants is they cannot be overwritten no matter what. You cannot overwrite a defined constant and you cannot unset a defined constant, either.

The following code will fail on the second line with a PHP notice informing us that MY_CONSTANT has already been defined. It cannot be redefined. Incidentally, you may check if a constant has already been defined using the defined function.

PHP:
define('MY_CONSTANT', 'TalkPHP.com');
define('MY_CONSTANT', 'WiredFlame.com');

The code below will simply out right fail with a syntax error as it is expecting a variable. Nothing more, nothing less.

PHP:
unset(MY_CONSTANT);

We Are Magic Constants

There are, however, a class of constants named magic constants that really aren't constants at all (I bet that confused you!). They are worth mentioning in the same article, though. Magic constants break the old mystical rule that constants cannot be overwritten. These constants begin with two underscores and typically end in two underscores as well. These are as follows:

  • __CLASS__: Stores the name of the current class it is in.
  • __FILE__: Contains the absolute path to the file.
  • __FUNCTION__: The function the constant is placed in.
  • __LINE__: Current line that the PHP parser is on.
  • __METHOD__: The current scope that the magic constant is in.

For the very reason that the magic constants exist, we can add another rule to our list of what constants can and cannot be or do. This is not crucial in the sense that PHP will crumble to its knees, but it is crucial if you want to ensure that when a new version of PHP is released that your script doesn't fail to work properly because you are now using a pre-defined magic constant.

PHP:
define('__CONSTANT__', 'TalkPHP.com');

Although the above example will work as of PHP version 5.2.4, the next version of PHP may use the __CONSTANT__ as a magic constant. Your script would then fail because you are attempting to overwrite a magic constant, which cannot be done but would not actually result in a PHP notice of any kind. That would really stump you!

How To Use Us

We have looked at how to define constants, we've even looked at magic constants which aren't really constants at all because they break the rules of typical constants, but how do we use constants throughout our scripts?

Let's begin with the most common method. Remember, this is:

PHP:
define('MY_CONSTANT', 'TalkPHP.com');

Once that has been issued to PHP we can simply echo out our constant. When echoing out constants we can go either of two ways. Either way we do not place a prefix on our constant like we do on variables. This means that:

PHP:
echo MY_CONSTANT; // will work
echo "MY_CONSTANT"; // will echo literally "MY_CONSTANT" so wrong
echo $MY_CONSTANT; // won't work

Constants and variables are in different namespaces and so in the previous example, the former would work and find our already defined constant, whilst the latter would look for a variable, but as we have not set it you will get the unpleasant PHP notice that the variable is undefined.

If you wish to use a constant dynamically. For instance, if you initiated a variable with the name of your constant, like so:

PHP:
$szMyConstant = 'MY_CONSTANT';

How could you then use that to echo the value of our constant? As you may well know, simply echoing the variable to the browser would literally print MY_CONSTANT and not the value of our constant, which would be TalkPHP.com. This is where you may wish to praise the existence of the constant function. Thanks to the introduction of the constant function we can echo the value of constants dynamically:

PHP:
$szMyConstant = 'MY_CONSTANT';
echo constant($szMyConstant);

Which would result in printing out TalkPHP.com and deliver a huge smile to your face at the same time. Perfect! Note that although the above code may seem superfluous because it'd be easier to do the following:

PHP:
$szMyConstant = MY_CONSTANT;
echo $szMyConstant;

The constant function would be useful in such instances where you are looping through constants. An instance where you do not know the exact name of the constants.

In this article, though, we have mentioned a much newer type of constant. The constants that can be defined directly within classes. These constants are not global to the entire script, but global to the entire class they were defined in. Take the following class with a defined constant:

PHP:
class TalkPHP
{
	const MY_CONSTANT = 'TalkPHP.com';
}

Echoing out its content is similar to the constants earlier on, but they must be echoed using the self:: scope to instruct PHP that the constant has been defined locally to the class, not defined locally to the entire script. This would echo out the value of our constant:

PHP:
public function __construct()
{
	echo self::MY_CONSTANT;
}

Constants local to the class itself are useful for if they are to be used only by the class and not the entire script. Having too many global constants can become overwhelming fairly quickly. It's also a security plus point, such as storing database credentials in a class constant would prevent anyone from echoing out the constant elsewhere in the script. Even issuing the following code would not work as a class constant cannot be accessed from an instance of an object:

PHP:
$pObject->MY_CONSTANT

That would fail with a PHP notice.

Closure

Now that you know how constants work you can use them throughout your projects. They make things much easier for you and allow for much better reading of your code by other individuals. To exemplify, if I was issuing flags to a script, such as in the glob function as mentioned in a previous article, then it's easier to read the following:

PHP:
$iFlags = GLOB_BRACE | GLOB_NOSORT;

Than it is to read:

PHP:
$iFlags = 128 | 32;

This is because GLOB_BRACE and GLOB_NOSORT actually mean something. They are not just random numbers that could mean absolutely anything unless you coded the script. Even the creators of the script would forget what the flags were after a while. Creating constants for your scripts is the way to go!

Most individuals who use constants also prefix their constants with the function or the script it is being used in. Such as if I was creating a function to check for Buddhists amongst the members and I wanted to use constants for a particular purpose. I would prefix my constants like so:

PHP:
define('BUDDHISTS_LEVEL', 8);
define('BUDDHISTS_GROUP', 16);

That way we know exactly which function or script our constants belong to. It also helps in applications, such as Zend Studio, that boast an auto-complete facility. You would type BUDDHISTS_ and the application would present you with a list of defined constants. Swish!

The truth is that constants are a godsend in the truest sense of the word. Just don't let anyone tell you otherwise!
 
1
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
0
•••
Thanks for the very informative post, was a good read!
 
0
•••
This is a very informative post on defining constants, I learned a lot from it myself.
Great Post, Rep added.
 
0
•••
i have been feeling so difficulty with defining constants


thanks brother for helping me and others like me
 
0
•••
  • The sidebar remains visible by scrolling at a speed relative to the page’s height.
Back