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.
The following will work just fine:
But the next example will result in an error:
The error displayed is like this:
Array Example
This is the same as for passing an object, but specify "array" as the type:
The first call to foo() will work just fine. The second one will result in an error like this:
Other types do not work
Unfortunately in PHP 5 you cannot type hint other types.
Trying to do this:
Will result in this error:
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).
0 comments:
Post a Comment