I’m : a programmer, writer, podcaster, geek, and coffee enthusiast.

PHP 5 supports forced argument types

I usually forget that this is possible. Usually, function arguments are declared without any type restrictions in PHP:

function whatever($a)  { /* ... */ }

But in PHP 5, you can specify argument types, as long as they’re classes (inheritance works):

class MyClass { /* ... */ }

function whatever(MyClass $a)  { /* ... */ }

Or array:

function whatever(array $a)  { /* ... */ }

These aren’t (and can’t be) enforced at “compile” time, but PHP will fail immediately upon calling a function with an invalid type-specified argument:

Catchable fatal error: Argument 1 passed to whatever() must be an array, integer given

This does not work with primitive types (int, string, float, etc.) because PHP assumes that they’re class names, and you don’t have a class named int. But testing this led me to discover something curious. This is valid PHP code:

class int { }
function t(int $a) { echo "hi\n"; }

t(new int);

var_dump((int) '1');

Sure enough, PHP figures this out:


That’s some impressively flexible keyword parsing by PHP. Not that this would be a good idea to ever use.