PHP 7 Type Hinting Example

This PHP 7 tutorial help to understand type hinting in PHP 7.The Type Hinting help to define arguments data type at the time of function declaration. You will get the fatal exception if required data type variable not passed into the method.

The PHP 5 also have type hinting but did not support scaler type. The PHP 7 support type hinting along with scalar data type.

What is scaler Data type in PHP 7

All of the data types which hold a single data item, those types are called scaler data type. The PHP 7 have char, int, short long, float, and double scalar (or base) data types.

You can also check varaible is scaler type or not using is_scalar() method.

PHP5 does not support type hinting to basic or scaler data types like string, integers, float etc. You can validate passed argument data type using “is_” family functions , Like is_string, is_integer etc.

Lest Start PHP 7 Type Hinting with Example:

We will create a simple example to demonstrate type hinting in PHP 7, I will create type hinting example based on integer, object and array.

Type Hinting in Scalar Data Type

Run the above program using PHP 7, You will get ‘1’ output.

If you run same above code into PHP5.6, Then You will get below PHP fatal error:

Error Argument 1 passed to integerTest() must be an instance of integer, integer given, called in /test.php

PHP Type Hinting in Array Type

Lets a create a PHP fucntion that will take arguments of the array type.I have below function that takes $vals varible as a parameters and it must be array data type.

Now we will called above method using integer data type:
arrayTest(1);

When you passed integer value into the above method, You will get below fatal error message:

FATAL ERROR Uncaught TypeError: Argument 1 passed to arrayTest() must be of the type array, integer given,

The above message clearly tells us: We have passed integer value but function expected array type argument.

Now we will call using array data type arguments:

The output:
Array ( [0] => 3 [1] => 4 [2] => 5 )

Type Hinting in Object Type

We can also do type hinting into the object type. Created a new Employee Class and passed the Person object as an argument into the constructor method.

Now, We will supply integer value to the Employee Class.
p1 = new Employee(1);

The output would be the fatal error:

FATAL ERROR Uncaught TypeError: Argument 1 passed to Employee::__construct() must be an instance of Person, integer given.

Lets passed the required arguments, which is Person class object, We will create Person class and set name into this object:

The output is:
parvez

Conclusion

This tutorial help to understand type hinting for PHP7 as well as with php 5.I have explained type hinting for the scalar types (strings,integers etc), array and object types.I hope its help you to understand type hinting in php7.