Saturday, December 8, 2007

Constants

Constants

Constants are containers just like variables for data, but once you've assigned a value to one, you can't change it in any way. Constants are defined using a separate method to variables in PHP (in some languages constants are declared in the same way, but using a keyword which defines them to be constant). Constants are created using the define() function in PHP:

    define("INDEPENDENCEDAY", "4th July");

Whenever you wish to reference it within the body of code, you can do so simply by using its name:

    echo(INDEPENDENCEDAY);

By convention, constants are given all uppercase names, although this is only a convention, and you're free to choose any name that conforms to the variable naming rules.

PHP constants are essentially meant to function in a similar way to C pre-processor #defines: you can declare them in one location, and execute different code later on depending on whether the constant was defined, or what value it was defined as. This is tested using the defined() function:

    if (defined("INDEPENDENCEDAY")) {
echo("INDEPENDENCEDAY is defined");
} else {
echo("INDEPENDENCEDAY is not defined");
}

No comments: