Variables and Types in PHP
Data types
The basic types are integer (32 bit signed quantity), double (32 float) and
string.
There is no boolean, instead 0, 0.0, and "" represent false.
Any other number or string represents true. In particular, "0" is
true even though 0 is false. An example of the three types can be
found at variables.php . Note how
the double does not print as it is listed in the source.
Values that exceed the size of an int are automatically converted to
a double. So $a=100000000000000000000000001 is really a double.
Variable Names
Names must start with a letter or "_". They may continue with a letter,
number, or "_". Variable names are case sensative, but built in function
names are not. WEIRD!
Constants
You can define constants within your code.
define("SCHOOL", "Northern Michigan");
echo(SCHOOL);
define("NL", "<br>\n"); |
Be convention constants have upper case names. Accessing the value
of a constant does NOT use a "$".
There are many predefined constants: TRUE, FALSE, PHP_VERSION,
PHP_OS, __FILE__, __LINE__.
Be careful with TRUE and FALSE, since not all values of TRUE and
FALSE are the same.
Type Conversion
Variables have the type of their contents, and that can change on the fly.
Strings are converted to numbers in a numeric context.
-
"2liter" evaluates to 2.
-
"catch22" evaluates to 0.
-
"3.4 children" evaluates to 3 (not 3.4).
-
"1e22" evaluates to 10000000000000000000000.
Numbers are converted to strings as needed, and in the obvious way.
Casting can be done just like in C++ or Java, or using the settype
command. The type of a variable can be determined by the gettype
command. The types for the gettype and settype commands are: integer,
double, string, array, object, class, and "unknown type".
There are convience functions is_integer(), is_double(), etc.
$a = 11.2; // a
is a double
$b = (int)$a; // b is an int
$c = (string)$a; // c is a string
if (settype($a, "integer")) {
echo("Converions YES");
}
else {
echo("Conversion NO");
}
$d = gettype($a); |
Useful Variable Functions
Name |
Example |
Explanation |
isset() |
isset($a) |
Is $a defined. Very useful to see if the form gave you and answer
(as opposed to being blank). |
unset() |
unset($a) |
Delete the variable, and free up space. |
empty() |
exmpty($a) |
The opposite of isset(). |
intval() |
intval($a, 16) |
Returns $a when interprated as an int written in base 16. Can
do any base, including binary. |