An addendum to the existing answer in PHP7 ceases to be called hinting type and is called type declaration 'cause this one now supports the guys int
, bool
, float
and string
, in addition to those already existing in php5, such as classes, interfaces, functions and arrays, I put a more detailed explanation in:
In practice the hinting type (php5) or type declaration php7 are optional and technically you can check the variables without using them, so for example:
PHP5
With induction of types:
<?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 induction of types:
<?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 see that it was necessary to create a if
and use is_int
, now in PHP7 you can do something like:
declare(strict_types=1);
function unixtimeToTimestamp(int $a) {
return gmdate('Y-m-d H:i:s', $a);
}
var_dump(unixtimeToTimestamp(1000203030));
//Causa erro
var_dump(unixtimeToTimestamp(1123123123.5));
of course in this case we use declare(strict_types=1);
to avoid some that would be considered implicit" for a "cast", such as float
for int
Completion
Notice how much easier it got with the hinting type or with the type declaration? That’s the basic purpose of it(s).
It is worth mentioning the
declare(strict_types=1)
that avoids the magic cast for the expected type?– Woss
This is new, right? It’s quoted :D
– Maniero