Tag Archive for 'spl'

SPL_Types in php and strong typing

A strong typed programming language is a programming language where the datatypes of values have restrictions on them. The restrictions apply for what datatypes can be stored in variables, whether or not you can operate on those variables and more. To have an overview of a good definition of a strong typed language, see Wikipedia.

By default, PHP isn’t strongly typed. PHP variables and class properties can hold every datatype you wish for, and while doing operations on them, PHP internally uses implicit type casting to convert the one type to another. For example, you could do the following:

1
2
3
4
5
$stringVal = "5";
$intVal = 3;
echo $stringVal + $intVal;
 
# outputs 8

The first variable is initialized as a string, the second variable is an int. In any strong typed language, this would probably throw an error. PHP on the other hand, internally evaluates the operation and typecasts the string value to an int. What happens internally is the value is given to the C function convert_to_double(val);, which then makes the add operation possible and returning the int value 8.

This approach is flexible and definitely has it’s benefits, but sometimes you do want a strongly typed language. Luckily there is a PECL extension just doing that: SPL_Types. The working of this is best illustrated with an example:

1
2
3
4
5
6
7
$int = new SplInt(3);
$float = new SplBool(3.53);
try {
    $int = 'string';
} catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}

As expected, this throws an Exception, because you tried to implicitly convert a integer to a string datatype. Similar SPL Classes exist for other datatypes too:

$int = new SplInt();
$float = new SplFloat();
$bool = new SplBool();
$enum = new SplEnum();

It’s available as a PECL extension, so the usual ‘pecl install SPL_Types‘ should do. It doesn’t make PHP a fully strong-typed language, but the SPL_Types extension isn’t meant to do so. It’s nice to have typing like this when you need it. To have a last example that might be of practical interest:

1
2
$input = $_GET['productCode']; # Unsafe way
$typeSafe = new SplInt($_GET['productCode']); # Type-safe way

Now, if anyone (maybe another developer) wants to change the input you receive from the $_GET['productCode'] key, if they try to do this:
$input = "myOwnProduct"; this will be perfectly valid, but not wanted. If you would do the same with our $typeSafe variable, an exception would be raised, telling you that the implicit typecast is not allowed, and thus improving security.