25 Aug 09 PHP Programming Tutorial: Constants



Constants are similar to PHP variables. They have a name and they store a value. Unlike variables, constants can not be changed. Once they’re given a value, they keep it. So if I created a constant for my bank account and set it to One Million Dollars, I could buy a thousand ice cream bars and still have a million dollars. That would be nice, wouldn’t it?

To create a constant, you define its name and its value, like so:

<?php define("constant-name","constant-value"); ?>

So to create my above example, I may do this:

<?php define("BANK_ACCOUNT","$1,000,000"); ?>
I have: <?php echo BANK_ACCOUNT; ?>!

Unlike variables, constant names do not start with a dollar sign ($). Constant names are usually UPPERCASE so you can easily tell it’s a constant, but you can use lowercase if you want.

Try to avoid naming your constants with words that PHP uses, like ECHO. For example, the following script would confuse PHP:

<?php
define("ECHO","Confusing");
echo ECHO; // Say what again?!
?>

PHP sees all of those echos and isn’t sure what to do, so it will throw an error at you.

When To Use Constants
As a general rule, if you know the value of something won’t change, then use a constant. If you ever need to update your script, using a constant allows you to quickly change the code without worrying if other parts of your script will change your intended value. Depending on the design and size of your PHP script, this could save you a lot of time.

Go back to Building PHP Scripts.

Tags: , , , ,

Leave a Comment