Constants are used to make sure a value does not change throughout the running of the script.
To define a constant, use the define() function, and include name of the constant, followed by the value for the constant, as shown here:
define( "MY_CONSTANT", "1" ); // MY_CONSTANT always has the string value "1"
<?PHP
define("aValue", 8);
print aValue;
?>
The code above generates the following result.
Pass in true as a third parameter to define() makes the constant case-insensitive:
<?PHP
define("SecondsPerDay", 86400, true);
print SecondsPerDay;
print SECONDSperDAY;
?>
The code above generates the following result.
The defined()
function is basically the constant equivalent of isset()
,
as it returns true if the constant string you pass to it has
been defined.
For example:
<?PHP
define("SecondsPerDay", 86400, true);
if (defined("Secondsperday")) {
// etc
}
?>
constant()
returns the value of a constant.
<?PHP
define("SecondsPerDay", 86400, true);
$somevar = "Secondsperday";
print constant($somevar);
?>
The code above generates the following result.
Use Math constant to calculate circle area
<?php //from ww w.j a v a 2s .co m
$radius = 4;
$diameter = $radius * 2;
$circumference = M_PI * $diameter;
$area = M_PI * pow( $radius, 2 );
echo "A radius of " . $radius . " \n ";
echo "A diameter of " . $diameter . " \n ";
echo "A circumference of " . $circumference . " \n ";
echo "An area of " . $area . " \n ";
?>
The code above generates the following result.