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.
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
?>
<?php
class text {
}
function term(array $text) {
echo 'Hello World!!';
}
$obj = new text(); // display Fatal error
term(123);
?>
Manish Kumar
25-Mar-2017