With Type Hinting we can force the parameter of the function to be object or an array. Type Hinting was introduced in PHP 5. Also we can allow NULL also along with object or array.
For forcing the parameter to be an object we have to specifying the name of the class in the function prototype.
Note: Type Hinting is not supported with int and string.
Let’s see how it works:
{
// We have forced the first parameter of below
// Method to be the object of the class second_class
// If you pass other data type or
// Even object of other class it will
// Generate Fatal Error
public function force_class(second_class $second_class)
{
/*
your code goes here
*/
}
// We have forced the first parameter of below
// method to be an array
// So it will generate fatal error if
// you pass parameter other than an Array
public function force_array(array $passed_array)
{
/*
Your code goes here
*/
}
}
class second_class
{
/*
Your code goes here
*/
}
class third_class
{
/*
Your code goes here
*/
}
$first = new first_class();
$second = new second_class();
$third = new third_class();
// Generate error, as string passed
$first->force_class("string");
// Generate error, as array passed
$first->force_class(array("1","2"));
// Generate error
// as object of other class passed
$first->force_class($third);
// This will work
// as object of second class passed
$first->force_class($second);
// Generate Error, as string passed
$first->force_array("string");
// This will works
$first->force_array(array("1","2"));
Type Hinting for Functions
We can use Type Hinting for functions which are outside the class. Let’s see how it works.
// Object of the first_class class
// as a first parameter.
function my_function(first_class $first)
{
/*
Your code goes here
*/
}
Allow NULL with Type Hinting
Yes, We can allow NULL values with the Type Hinting. So in that case parameter must be as per the defined type or it should be NULL.
// Must be an object of the class first_class
// or NULL
function allow_null(first_class $first = NULL)
{
/*
Your Code Goes Here
*/
}
// This works
$first = new first_class();
allow_null($first);
// This also works
allow_null(NULL);
Type Hinting for Array was introduced in PHP 5.1. Type Hinting is not supported with int and string.