Type hinting in php

With Type hinting we can specify the expected data type (arrays, objects, interface, etc.) for an argument in a function declaration. This practice can be most advantageous because it results in better code organization and improved error messages.It will also explain the subject of type hinting for basic data types (integers, floats, strings, and booleans) which is only supported in PHP7

Since PHP 5 you can use type hinting to specify the expected data type of an argument in a function declaration. When you call the function, PHP will check whether or not the arguments are of the specified type. If not, the run-time will raise an error and execution will be halted.

Valid types are class names for arguments that receive objects and array for those that receive arrays. Here’s an example:

function enroll(Student $student, School $school) {
echo "Enrolling " . $student->name . " in " . $school->name;

By telling PHP exactly what kind of objects the enroll() method expects to receive, you can ensure that students are being enrolled in a school instead of a nunnery or a 401K. Likewise, you know that you won’t have any stubborn pachyderms showing up for the first day of third grade.

What would happen if I tried to enroll myself into medicare?

$me = new Student("Amanda");
$medicare = new Program("Medicare");
$enroll = enroll($me, $medicare);

Although I am a student, the following error would occur:

Catchable fatal error: Argument 2 passed to enroll() must be an instance of School, instance of Program given, called in typehint.php on line 32 and defined in typehint.php on line 6

If null is used as a default value for an argument it will also be allowed. Here’s an example, this time with arrays:

function startParty(array $guests, array $food = null) {
    // party stuff...

$guests = array("Susan Foreman", "Sarah Jane Smith", "Rose Tyler", "Donna Noble");
startParty($guests, null);


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:

 1 2 3 4function functionName (array $argumentName)

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.

 1 2 3 4 5 6 7 8 91011// 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:


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).

 1 2 3 4 5 6$models = array(
  array('Toyota', 12, 44),
  array('BMW', 13, 41)

Toyota : 528
BMW : 533

Now it’s working because we passed to the function the array that it expected to get.

How to do object type hinting?

Type hinting can also be used to force a function to get an argument of type Object. For this purpose, we put the name of the class in front of the argument name in the function.

In the following example, the class’s constructor can only get objects that were created from the Driver class. We ensure this by putting the word Driver in front of the argument name in the constructor.

 1 2 3 4 5 6 7 8 910111213141516class Car {
  protected $driver;
  // The constructor can only get Driver objects as arguments.
  public function __construct(Driver $driver)
    $this -> driver = $driver;
class Driver {}
$driver1 = new Driver();
$car1    = new Car($driver1);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s


Up ↑

%d bloggers like this: