PHP 7 - Dichiarazioni del tipo di ritorno
In PHP 7, una nuova funzionalità, Return type declarationsè stato introdotto. La dichiarazione del tipo restituito specifica il tipo di valore che una funzione deve restituire. È possibile dichiarare i seguenti tipi di tipi restituiti.
- int
- float
- bool
- string
- interfaces
- array
- callable
Esempio: tipo restituito valido
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value;
}
print(returnIntValue(5));
?>
Produce il seguente output del browser:
5
Esempio: tipo restituito non valido
<?php
declare(strict_types = 1);
function returnIntValue(int $value): int {
return $value + 1.0;
}
print(returnIntValue(5));
?>
Produce il seguente output del browser:
Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...