Type Hinting in PHP5
Recently i have prepared some OOPs demos for my students and i really like one concept is Type Hinting so let’s have a quick look at Type Hinting. Type Hinting is a new concepts of OOPs in PHP and its included in PHP5.Type Hinting is one kind of function which force to arguments to be an Object or an array.
let’s see some basic and common example which shows you type hinting with function,with array and Object, With Allow NULL
NOTE: Type Hinting is not supported with int and string data types.
Basic Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
class Type_hint{
function hint_method(array $arr){
print_r($arr);echo "<br/>";
}
}
class Type_hint_new
{
function hint_object(Type_hint $obj){ // Here, If I didn’t pass in an Type_hint object to hint_object(), a FATAL_ERROR was occured.
//echo $obj->hint_method(); // Fatal Error: Argument must be an array
echo $obj->hint_method(array('P','H','P')); //First parameter must be an object of Type_hint class
}
function hint_null($obj = NULL) {
echo "Allow NULL";
}
}
$obj=new type_hint();
$obj_new = new Type_hint_new();
$obj->hint_method(array('b','h','u','m','i'));
$obj_new->hint_object($obj);
$obj_new->hint_null(NULL); |
Now lets check the type hint results:
|
1 2 3 |
Array ( [0] => b [1] => h [2] => u [3] => m [4] => i )
Array ( [0] => P [1] => H [2] => P )
Allow NULL |
NOTE: To check errors of type-hints,new error level E_RECOVERABLE_ERROR is implemented from PHP5
Type hinting works with interfaces and abstract class too.








Wow, that’s a ralely clever way of thinking about it!