PHP Constants

From Techotopia
Revision as of 13:57, 29 May 2007 by Neil (Talk | contribs)

Jump to: navigation, search

If you look up the word constant in a dictionary it will probably tell you that the word is used to describe something that is non-changing and non-variable, and this is exactly the purpose of constants in PHP. A PHP constatnt is the opposite of a variable in that once it has been defined it cannot be changed.

Constants are particularly useful for defining a value that you frequently need to refer to that does not ever change. For example, you might define a constant called INCHES_PER_YARD that contains the number of inches in a yard. Since this is a value that typically doesn't change it makes sense to define it as a constant. Conversely, a value that is likely to change, such as the Dollar to Yen exchange rate is best defined as a variable.

PHP constants are said to have global scope. This basically means that once you have defined a constant it is accessible from any function or object in your script.

In addition, PHP provides a number of built-in constants that are available for use to make life easier for the PHP developer.

Defining a PHP Constant

Rather than using the assignment operator as we do when defining variables, constants are created using the define() function. Constants also lack the $ prefix of variable names.

The define function takes two arguments, the first being the name you wish to assign to the constant, and the second the value to assign to that name.

Constant name are case sensitive and, althouth it is not a requirement, convention carried over from other programming languages, dictates that constants should be named in all upper case characters. The following example demonstrates the use of the define() function to specify a constant:

<?php
define('INCHES_PER_YARD', 36);
?>