Working with Types

PHP is a loosely typed language, allowing variables and function parameters to be set to any type of data. Similarly, functions can return different data types in different circumstances.

In the last section, we introduced the function prototype as a way of describing the type of parameters that functions are designed to work with and the types of data that are returned. Since PHP is loosely typed, PHP can't enforce these types as strongly typed languages do. To illustrate this, the PHP library function strtoupper( ) is designed to operate on strings, but can be called with an integer parameter:

$var = 42;

print strtoupper($var); // prints the string "42"

When functions are designed to work with different data types, prototypes describe parameters and return values as mixed. Other functions may not work as expected, or may not work at all, when the wrong type of data is used.

Type Conversion

PHP provides several mechanisms to allow variables of one type to be considered as another type. Variables can be explicitly converted to another type with the following functions:

string strval(mixed variable)
integer intval(mixed variable [, integer base])
float floatval(mixed variable)

The functions convert the variable into a string, integer, or float respectively. The intval( ) function also allows an optional base that determines how the variable is interpreted.

$year = 2003; // Sets $yearString to the string value "2003" $yearString = strval($year); $var = "abc"; // sets ...

Get Web Database Applications with PHP and MySQL, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.