PHP 7 Return Type Declarations

Return Type Declarations has been introduced in PHP 7.It specify the type of value that a function should return.

The following types can be assigned to function return value.

  • strings
  • float
  • int
  • bool
  • interfaces
  • callable
  • array

Valid Return Type Example in PHP 7

<?php
declare(strict_types = 1); // Strict mode
   function returnIntVal(int $value): int {
      return $value;
   }
   print(returnIntVal(7));
?>

OutPut

The above example will output: 7

Invalid Return Type Example in PHP 7

<?php
declare(strict_types = 1); // Strict mode
   function returnIntVal(int $value): int {
      return $value+2.0;
   }
   print(returnIntVal(7));
?>

OutPut

The above example will output: "PHP Fatal error: Uncaught TypeError: Return value of returnIntVal() must be of the type integer".