Home > DeveloperSection > Blogs > Type Hinting in PHP

Type Hinting in PHP


PHP PHP 
Ratings:
0 Comment(s)
 125  View(s)
Rate this:

Type Hinting in PHP


Type Hinting is a technique that hints the function to accept only given data types. In PHP we can use type hinting for array, object and callable data type. Type hinting is introduced from PHP5. Basically, type hinting is a method that we can specify expected data (array, object, interface, etc) for an argument in a function declaration. It is advantageous because it will give result in better way and improve the error messages. In this part we will discuss about how in PHP 5 type hinting works.

Following is a class/object example:

 

In the below example text() is a class and term() is a function. The term() method takes only one parameter which is an object of text type. The Type of $text should be specified before the variable.

<?php

class text {

}

 

function term(text $text) {   // text is a object type for $text and should always be written before $text

echo 'Hello World!!';

}

$obj = new text();;

term($obj);        // display Hello World

?>

 

In the above example, it clearly specifies the type of $text which should always be an object type. Now let’s see one more example which will give the error:

<?php

class text {

}

 

function term(foo $text) {

echo 'Hello World!!';

}

$obj = new text();;     // display Fatal error

term($obj);

?>

For the above example it will display fatal error as there is no such foo type object is found in the code.

Output:

Fatal error: Uncaught TypeError: Argument 1 passed to term() must be an instance of foo, instance of text given

 

Type Hinting in Array

In the below example text() is a class and term() is a function. The term() method takes only one parameter which is an array type. The Type of $text should be specified before the variable.

<?php

class text {

}

 

function term(array $text) {   // type should be array only

echo 'Hello World!!';

}

$obj = new text();;

term(array($obj));   // display Hello World

?>

 

In the above example, it clearly specifies the type of $text which should always be an array type. Now let’s see one more example which will give the error:

<?php

class text {

}

 

function term(array $text) {

echo 'Hello World!!';

}

$obj = new text();     // display Fatal error

term(123);

?>

 

For the above example it will display fatal error, argument must be array type but integer given.

Output:

Fatal error: Uncaught TypeError: Argument 1 passed to term() must be of the type array, integer given

 


Don't want to miss updates? Please click the below button!

Follow MindStick