PHP 7 - Declarações de tipo de retorno

No PHP 7, um novo recurso, Return type declarationsfoi introduzido. A declaração do tipo de retorno especifica o tipo de valor que uma função deve retornar. Os seguintes tipos de tipos de retorno podem ser declarados.

  • int
  • float
  • bool
  • string
  • interfaces
  • array
  • callable

Exemplo - Tipo de retorno válido

<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value;
   }
   print(returnIntValue(5));
?>

Ele produz a seguinte saída do navegador -

5

Exemplo - Tipo de retorno inválido

<?php
   declare(strict_types = 1);
   function returnIntValue(int $value): int {
      return $value + 1.0;
   }
   print(returnIntValue(5));
?>

Ele produz a seguinte saída do navegador -

Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type integer, float returned...