Type hinting with PHP

Posted in PHP -

PHP has supported type hinting for parameter functions from version 5.0 for objects and from version 5.1 for arrays. Type hinting means the function specifies what type the parameter must be and if it is not of the correct type an error will occur. Type hinting is not supported for other types, e.g. for strings and integers.

Class/Object Example

The first example has a class called "bar" and a function called "foo". The function "foo" takes a single parameter which must be an object of "bar" type. The type that $foo should be is specified by putting the class name before the variable in the parameter list.

class bar {
}

function foo(bar $foo) {
}

The following will work just fine:

$bar = new bar;
foo($bar);

But the next example will result in an error:

$bar = new some_other_class_that_is_not_bar;
foo($bar);

The error displayed is like this:

Catchable fatal error: Argument 1 passed to foo() must be an instance 
of bar, instance of some_other_class_that_is_not_bar given, called in ... 

Array Example

This is the same as for passing an object, but specify "array" as the type:

function foo(array $foo) {
}

foo(array(1, 2, 3)); // good
foo(123); // bad

The first call to foo() will work just fine. The second one will result in an error like this:

Catchable fatal error: Argument 1 passed to foo() must be an array, 
integer given, called in ...

Other types do not work

Unfortunately in PHP 5 you cannot type hint other types.

Trying to do this:

function foo(string $foo) {
}
foo('testing');

Will result in this error:

Catchable fatal error: Argument 1 passed to foo() must be an instance 
of string, string given, called in ...

Why type hint?

Type hinting ensures the type of class (or array) being passed to the function is correct and as expected. It can also help with code completion in an IDE (at least it does with NuSphere PhpED).



Related posts:


Comments