An addition to the existing answer in PHP7 ceases to be called type hinting and is called type declaration since this now supports the types int
, bool
, float
and string
, in addition to the existing ones in php5, like classes, interfaces, functions and arrays, I've put a more detailed explanation on:
In practice, type hinting (php5) or type declaration php7 are optional and technically you can check variables without using them, for example:
PHP5
With type induction:
<?php
function filterLetters($a) {
if (is_array($a)) {
return array_filter($a, 'ctype_alpha');
}
return false;
}
//Causa erro
var_dump(filterLetters(array('a', 'b', 'cdef', 0, 1, 3, 'a1')));
//Causa erro
var_dump(filterLetters('abc'));
With type induction:
<?php
function filterLetters(array $a) {
return array_filter($a, 'ctype_alpha');
}
//retorna array(a, b, cdef)
var_dump(filterLetters(array('a', 'b', 'cdef', 0, 1, 3, 'a1')));
//causa erro
var_dump(filterLetters('abc'));
PHP7
No type declaration:
function unixtimeToTimestamp($a) {
if (is_int($a)) {
return gmdate('Y-m-d H:i:s', $a);
}
return false;
}
//Retorna algo como 2001-09-11 10:10:30
var_dump(unixtimeToTimestamp(1000203030));
//Retorna false
var_dump(unixtimeToTimestamp(1123123123.5));
However, you have to create a if
and use is_int
, now in PHP7 you can do something like:
function unixtimeToTimestamp(int $a) {
return gmdate('Y-m-d H:i:s', $a);
}
var_dump(unixtimeToTimestamp(1000203030));
//Causa erro
var_dump(unixtimeToTimestamp(1123123123.5));
Conclusion
Did you notice how easy it became with type hinting or type declaration ? This is his basic purpose.