Page 78 - Beginning PHP 5.3
P. 78
Part II: Learning the Language
Why would you want to change a variable ’ s type with settype() , or change a value ’ s type with
casting? Most of the time, PHP ’ s loose typing handles type conversion for you automatically, depending
on the context in which you use variables and values. However, forcing a variable to be of a certain type
is useful for security reasons; if you ’ re expecting to pass a user - entered integer value to a database, it ’ s a
good idea to cast the value to an integer, just to make sure the user really did enter an integer. Likewise,
if you ’ re passing data to another program, and that program expects the data to be in string format, you
can cast the value to a string before you pass it.
Essentially, use explicit casting or settype() whenever you want to be absolutely sure that a variable
contains data of a certain type.
Operators and Expressions
So far you ’ ve learned what variables are, and how to set a variable to a particular value, as well as how
to retrieve a variable ’ s value and type. However, life would be pretty dull if this was all you could do
with variables. This is where operators come into play. Using an operator, you can manipulate the
contents of one or more variables to produce a new value. For example, this code uses the addition
operator ( + ) to add the values of $x and $y together to produce a new value:
echo $x + $y;
So an operator is a symbol that manipulates one or more values, usually producing a new value in the
process. Meanwhile, an expression in PHP is anything that evaluates to a value; this can be any
combination of values, variables, operators, and functions. In the preceding example, $x + $y is an
expression. Here are some more examples of expressions:
$x + $y + $z
$x - $y
$x
5
true
gettype( $test_var )
The values and variables that are used with an operator are known as operands .
Operator Types
Operators in PHP can be grouped into ten types, as follows:
Type Description
Arithmetic Perform common arithmetical operations, such as addition and
subtraction
Assignment Assign values to variables
Bitwise Perform operations on individual bits in an integer
40
9/21/09 8:51:23 AM
c03.indd 40 9/21/09 8:51:23 AM
c03.indd 40