php.w3clubs.com

PHP tutorials and articles

 

Constants

A constant is like a variable but its value cannot be changed once it's set, hence the name "constant".

Using constants

Constants are named like variables, but have no $ sign before the name. Example:

echo MY_CONSTANT;

Constant names can be of any case, like MyConstant, my_constant, or MY_CONSTANT, but it's a good idea to always have them all uppercased, so that they are easily recognizable when you look at the code.

If you attempt to use a constant that is not yet defined, you'll get a notice when error reporting is set to E_ALL and the value of the undefined constant will be assumed to be the name of the constant. In the code above if MY_CONSTANT was not defined, you'll see something like:

Notice: Use of undefined constant MY_CONSTANT - assumed 'MY_CONSTANT' in Command line code on line 1
MY_CONSTANT

Setting a constant value

To set the value of a constant, use the define() function, like so:

define('MY_CONSTANT', 123);
echo MY_CONSTANT; // prints 123

If you try to set the same constant twice, you'll get a notice (not an error). To avoid this you can call the function defined() to check if a constant is already set before you attempt to define it.

if (!defined('MY_CONSTANT')) {
    define('MY_CONSTANT', 2007);
}

Constant values

Only scalar values can be assigned to a constant, meaning numbers, strings, booleans. You cannot store an array in a constant.

Application

One good example use of constants is to use them instead of hardcoding values. Every time you find yourself thinking something like "Hmm, I think I'll have 12 photos per page" and you hard code 12 in your code, stop for a moment and define a constant at the top of the script.

define('PHOTOS_PER_PAGE', 12);

« to the PHP tutorial table of contents

Leave a Reply

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Powered by WordPress, theme by ♣w3clubs.com, based on Kubrik and Sancta Simplicitas