Classe TypeError
Dalla versione 7 di PHP, come visto nell’articolo precedente, abbiamo a disposizione una nuova classe che permette di gestire gli errori di tipo; in un esempio come quello sopra possiamo gestire in autonomia l’errore:
declare(strict_types=1);
// Coercive mode
function sumOfInts(int ...$ints)
{
//echo gettype($ints)."\n";
return array_sum($ints);
}
try {
var_dump(sumOfInts(2, '3', 4.1));
} catch (TypeError $e) {
echo 'Errore di tipo: '.$e->getMessage()."\n";
}
Output:
Errore di tipo: Argument 3 passed to sumOfInts() must be of the type integer, float given, called in /var/www/html/php7/2.php on line 13
Commenti recenti