LearnType hinting

Type hinting

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.

This tutorial will start by explaining the subject of type hinting for arrays and objects which is supported in both PHP5 as well as PHP7.

It will also explain the subject of type hinting for basic data types (integers, floats, strings, and booleans) which is only supported in PHP7.

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.

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.

class 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);

Does PHP support type hinting to basic data types?

It depends.

Whereas PHP5 doesn’t allow type hinting for basic data types (integers, floats, strings and booleans), PHP7 does support scalar type hinting.

PHP5 does not support type hinting to basic data types like integers, booleans or strings. So, when we need to validate that an argument belongs to a basic data type, we can use one of PHP’s “is_” family functions. For example:

  • is_bool - to find out whether a variable is a boolean (true or false).
  • is_int - to find out whether a variable is an integer.
  • is_float - to find out whether a variable is a float (3.14, 1.2e3 or 3E-10).
  • is_null - to find out whether a variable is null.
  • is_string - to find out whether a variable is a string.

On the other hand, PHP7 does support scalar type hinting. The supported types are: integers, floats, strings, and booleans.

The following code example can only work in PHP7.

class car {
  protected $model;
  protected $hasSunRoof;
  protected $numberOfDoors;
  protected $price;

  // string type hinting
  public function setModel(string $model)
  {
    $this->model = $model;
  }

  // boolean type hinting
  public function setHasSunRoof(bool $value)
  {
    $this->hasSunRoof = $value;
  }

  // integer type hinting
  public function setNumberOfDoors(int $value)
  {
    $this->numberOfDoors = $value;
  }

  // float type hinting
  public function setPrice(float $value)
  {
    $this->price = $value;
  }        
}

Conclusion

In this tutorial, we explained type hinting for the array and object data types as well as for the scalar data types (integers, floats, strings, and booleans), but did not explain how to do it for interfaces. However, the use of type hinting for interfaces can yield many benefits, as will be explained in the next tutorial.

But before we move on to the next lesson, lets practice: Practice type hinting

comments powered by Disqus