PHP Type Hinting


 

PHP Type Hinting

Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type

Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array.If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type

PHP Type Hinting Function:

Type hinting is a special type of function which is introduced in PHP version 5. This function is used to explicitly typecast a value into objects of a class or to an array. Type Hints only supports object and array type, other primitive types like int and string are not supported.

Go through each example and read the error message carefully then you will come to know about the cause of the error and type hinting more preciously.

If the datatype (class or array) of actual argument does not match with the formal argument then an error message will be automatically generated. This is applicable to only object of any class type or array type.

Example :

<?php
class One{
function arraytest(array $arr){
print_r ($arr);
}
}
$one=new One;
$one->arraytest("a string");
?>

Output:

Catchable fatal error: Argument 1 passed to One::arraytest() must be an array, string given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 10 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.

Example :

<?php
class One{
function arraytest(array $arr){
print_r ($arr);
} 
}
$one=new One;
$one->arraytest(array('a','s'));
?>

Output:

Array ( [0] => a [1] => s ) Array ( [0] => a [1] => s )  

Example:

<?php
class One{
function other_class_test(Two $two){
echo $two->var;
} 
}
class Two{
public $var="This is a variable ";
}
$one=new One;
$obj=new Two;
$one->other_class_test($obj);
?>

Output:

This is a variable .

Example:

<?php
class One{
function other_class_test(Two $two){
echo $two->var;
} 
}
class Two{

public $var="This is a variable ";
}
class NewClass
{
public $var="Another variable";
}
$one=new One;
$obj=new NewClass;
$one->other_class_test($obj); 
?>

Output:

Catchable fatal error: Argument 1 passed to One::other_class_test() must be an instance of Two, instance of NewClass given, called in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 17 and defined in C:\xampp\htdocs\PHP-AJAX\type-hinting.php on line 3.

Ads