1. Constants
Constants are values like variables but cannot be changed afterwards.
Additional they cannot be used for every type as for variables. They can
only use scalar values
and the special value NULL. In difference to variables constants
can be accessed everywhere in your php scripts, even inside functions.
Constants are often used for settings and parameters like
error_reporting.
2. Defining and usage of constants
You can define a constant with the function define. The first parameter is the name, the second parameter is the value of the constant.
<?php
define('SITE_NAME', 'My cool homepage');
?>
Constants uses the same name convention like variables (explude the
dollar character $ of course). However constants
are typically written in uppercase.
To access a constant simply use its name.
<?php
echo SITE_NAME;
// or like:
echo 'Welcome on '.SITE_NAME.'!';
// but not:
echo 'Welcomeon SITE_NAME!'; // won't find it as a constant, its a simple string
?>
3. Usage of constants
Constants are used for predefined functions as parameters which may be only integers or as return values which may be only integers. These contants are predefined as got useable names. As an example the function getimagesize returns some information about an image. The type of the image (png, jpeg, gif, ...) is encoded as an integer. The value 1 is for gif and the value 4 is for png. To check agains the type you could write the following code.
<?php
if (1 == $imagetype) {
} else if (4 == $imagetype) {
}
?>
Instead of looking in the manual all the time what 1 and
4 means you should use the predefined constants instead.
<?php
if (IMAGETYPE_GIF == $imagetype) {
} else if (IMAGETYPE_PNG == $imagetype) {
}
?>
Everyone understand what these if statements are checking. This is also used for parameters. As an example the function error_reporting expect an integer. This integer encodes by the bits it is used which errors are shown and which not. A valid function call would be the following:
<?php
error_reporting(8191);
?>
However noone will knows what this value means. In this case you should use
the E_* instead.
<?php
error_reporting(E_ALL | E_STRICT);
?>
Besides that the values of the constants can be changed for different
php versions. The value of E_ALL is in php version 5.2.x
6143, but before this version it was 2047.
If you use the value 2047 instead of the constants the
same script may be run differently on an other php version.
If you use the constants instead it runs the same all the time
as the current php version knows the right value for E_ALL
and use the proper integer value for this function.