[Previous] [Contents] [Next]


Variables


Variables in PHP are identified by a dollar sign followed by the variable name. Variables don't need to be declared, and they have no type until they are assigned a value. The following code fragment shows a variable $var assigned the value of an expression, the integer 15. Therefore, $var is defined as being of type integer.

$var = 15;

Because the variable in this example is used by assigning a value to it, it's implicitly declared. Variables in PHP are simple: when they are used, the type is implicitly defined-or redefined-and the variable implicitly declared.

The variable type can change over the lifetime of the variable. Consider an example:

$var = 15;
$var = "Sarah the Cat";

This fragment is acceptable in PHP. The type of $var changes from integer to string as the variable is reassigned. Letting PHP change the type of a variable as the context changes is very flexible and a little dangerous.

Variable names are case-sensitive in PHP, so $Variable, $variable, $VAriable, and $VARIABLE are all different variables.

One of the most common sources of bugs in PHP is failing to detect that more than one variable has accidentally been created. The flexibility of PHP is a great feature but is also dangerous. We discuss later how to set the error reporting of PHP so that it creates warning messages sensitive to unassigned variables being used.


[Previous] [Contents] [Next]