Specifications

Type Strength
PHP is a very weakly typed language. In most programming languages, variables can only
hold one type of data, and that type must be declared before the variable can be used, as in C.
In PHP, the type of a variable is determined by the value assigned to it.
For example, when we created $totalqty and $totalamount, their initial types were deter-
mined, as follows:
$totalqty = 0;
$totalamount = 0.00;
Because we assigned 0, an integer, to $totalqty, this is now an integer type variable.
Similarly, $totalamount is now of type double.
Strangely enough, we could now add a line to our script as follows:
$totalamount = “Hello”;
The variable $totalamount would then be of type string. PHP changes the variable type
according to what is stored in it at any given time.
This ability to change types transparently on-the-fly can be extremely useful. Remember PHP
automagicallyknows what data type you put into your variable. It will return the data with
the same data type once you retrieve it from the variable.
Type Casting
You can pretend that a variable or value is of a different type by using a type cast. These work
identically to the way they work in C. You simply put the temporary type in brackets in front
of the variable you want to cast.
For example, we could have declared the two variables above using a cast.
$totalqty = 0;
$totalamount = (double)$totalqty;
The second line means Take the value stored in $totalqty, interpret it as a double, and store
it in $totalamount.The $totalamount variable will be of type double. The cast variable does
not change types, so $totalqty remains of type integer.
Variable Variables
PHP provides one other type of variablethe variable variable. Variable variables enable us to
change the name of a variable dynamically.
PHP Crash Course
C
HAPTER 1
1
PHP CRASH
COURSE
23
03 7842 CH01 3/6/01 3:39 PM Page 23