How to do array type hinting?
When we would like to force a function to get only arguments of the type array, we can put the keyword array in front of the argument name, with the following syntax:
function functionName (array $argumentName)
{
//code
}
In the following example, the calcNumMilesOnFullTank() function calculates the number of miles a car can be driven on a full tank of gas by using the tank volume as well as the number of miles per gallon (mpg). This function accepts only array as an argument, as we can see from the fact that the argument name is preceded by the array keyword.
// The function can only get array as an argument.
function calcNumMilesOnFullTank(array $models)
{
foreach($models as $item)
{
echo $carModel = $item[0];
echo " : ";
echo $numberOfMiles = $item[1] * $item[2];
echo "<br />";
}
}
First, let's try to pass to the function an argument which is not an array to see what might happen in such a case:
calcNumMilesOnFullTank("Toyota");
Result:
Catchable fatal error: Argument 1 passed to calcNumMilesOnFullTank() must be of the type array, string given
This error is a precise description of what went wrong with our code. From it, we can understand that the function expected an array variable, and not a string.
Let's rewrite the code and pass to the function an array with the expected items, including the model names, the tank volumes, and the mpg (miles per gallon).
$models = array(
array('Toyota', 12, 44),
array('BMW', 13, 41)
);
calcNumMilesOnFullTank($models);
Result:
Toyota : 528
BMW : 533
Now it's working because we passed to the function the array that it expected to get.