Page 87 - Beginning PHP 5.3
P. 87
Chapter 3: PHP Language Basics
Constants are useful for any situation where you want to make sure a value does not change throughout
the running of your script. Common uses for constants include configuration files and storing text to
display to the user.
Try It Out Calculate the Properties of a Circle
Save this simple script as circle_properties.php in your Web server ’ s document root folder, then
open its URL (for example, http://localhost/circle_properties.php ) in your Web browser
to run it:
< ?php
$radius = 4;
$diameter = $radius * 2;
$circumference = M_PI * $diameter;
$area = M_PI * pow( $radius, 2 );
echo “This circle has... < br / > ”;
echo “A radius of “ . $radius . “ < br / > ”;
echo “A diameter of “ . $diameter . “ < br / > ”;
echo “A circumference of “ . $circumference . “ < br / > ”;
echo “An area of “ . $area . “ < br / > ”;
? >
When you run the script, you should see something like Figure 3 - 1 .
Figure 3 - 1
How It Works
First, the script stores the radius of the circle to test in a $radius variable. Then it calculates the
diameter — twice the radius — and stores it in a $diameter variable. Next it works out the circle ’ s
circumference, which is π (pi) times the diameter, and stores the result in a $circumference variable.
It uses the built - in PHP constant, M_PI , which stores the value of π .
49
9/21/09 8:51:27 AM
c03.indd 49
c03.indd 49 9/21/09 8:51:27 AM