Variables and Constants
Introduction.
Variables in PHP have a fairly unique style. Like most scripting
languages it doesn't do a great job of distinguishing/declaring variables
types up front. For example, think of the Dim statements in VBScript
ASPs and the var in JavaScript where everything seems to be treated like
the old Basic catch all data type ______. Yet variable types are distinguished internally without explicit statements. This is probably considered user friendly by many. As a teacher I consider it dangerous and likely to lead to bad habits in students. But never the less, we will make use of variables in the ways that seem to be conventional in PHP. In general, variables are identifiers used to store and access values. In PHP they can be
PHP has certain syntactic rules for naming variables.
We will do much more with variables after I introduce forms, but until then you should work with the following PHP script called very_basic_variables.php. |
<html> <head> <title>Some Very Basic Work With Variables</title> </head> <body bgcolor="005544" text="d0d0d0"> <?php // assigning the information and displaying it $first_number = 1.234; print "The first variable \$first_number has value <b>$first_number</b><BR>"; $second_number = 37.33; print "The second variable \$second_number has value <b>$second_number</b><BR>"; $product = $first_number * $second_number; print "The product of these two numbers \$product is <b>$product </b>"; ?> </body> </html> |
It is also possible to define constants within PHP scripts. The next example will set a value for PI and use it to compute the area of a circle. You should call this file very_basic_constants.php. |
<html> <head> <title>Some Very Basic Work With Variables</title> </head> <body bgcolor="005544" text="d0d0d0"> <?php // assigning the information and displaying it $radius = 5; print "The radius \$radius has value <b>$radius</b><BR>"; define('PI', 3.14159); print "The universal constant \PI has value <b>PI</b><BR>"; $area = PI * $radius * $radius; print "The area of the circle, \$area is <b>$area </b>"; ?> </body> </html> |
Notice how the constant PI does not have any preceding
$. It is also a fairly standard convention to spell constants with
all capital letters. I reiterate that we will get more involved with these as we go through the semester. In addition, quite quickly we will work with forms so that we can process user inputs and not be restricted to these very artificial situations where variables are assigned only within the script. |