PHP Type Hinting

Type hinting allows function to only accept specific data type as arguments.

In the case where an argument passed of an invalid type is passed to a function a run time error is thrown at the point of execution.

The concept in PHP of type hint has been available since PHP 5.1

function count(array $students) {
    echo count($students);

The snippet above describes a find function that expects to get an object of class User and parameter as arguments.

You can type hint for array, scalar type like int, string, bool, and more depending on your version of PHP. For an exhaustive see here.

In the case when the values passed don’t meet that requirement like below:

function find(Student $student, University $school) {
    echo "Locating " . $student-&gt;firstname . " from " . $school -> name;

$student = new Student();
$college = new HighSchool();

find($student, $college)

Given that Student, HighSchool, University classes exist an FATAL like the below is thrown.

FATAL ERROR Uncaught TypeError: Argument 2 passed to find() must be an instance of University, instance of HighSchool given

Some benefits to type hinting functions include:

  • Its a great way to have your code act as documentation because it tells you what type of data is to be expected.
  • Its encourages a cleaner and clearer code design because it forces developers to think of the specific data type required by a function.

Type hinting has helped me improve my coding style and ability. I’d encourage you to give it a try.

Related Posts