If you have any suggestions or comments, and would prefer using email, please contact me at:
gngabriel29[REMOVETHISANDREPLACEWITHYOU-KNOW-WHAT]ymail.com

September 30, 2008

PHP: Using constants

Filed under: PHP/PHP Basics


We will be learning how to use constants.

The difference between a constant and variable, is a constant can only be defined once, i.e. its value can only be set one time, while a variable can have its value changed many times throughout the running of the program.

One reason to use constants is to set values that you know will should not change during the running of the program, such as interest rates, or other values which should not change while the PHP program is running.

In this case, I create a constant called AGE, and set a value of 18 to it, by using the following code:
define(”AGE”,18);

Define AGE constant

You can then echo or output in browser the value of the constant called AGE, using the following code:
echo AGE;

Define AGE constant, browser output

Note: you cannot define the same constant more than one time, during the course of the program running, otherwise notice message will be given, informing you that the constant has already been defined. This means that a constant value once set cannot be changed.

Define AGE constant more than once
defining the same constant more than one time

Define AGE constant more than once, browser output
defining the same constant more than one time causes notice message to be displayed

Note: the value of AGE constant will still be 18, even though the second define statement tries to change it to 21, because a constant can ONLY be defined once.

Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href=""> <b> <blockquote> <code> <em> <i> <strike> <strong>. I unfortunately do not have a spoiler-code, so be sure mark spoilers well.



Anti-spam measure: please retype the above text into the box provided.