PHP 7 – Return Type Declarations

PHP 7 introduced another new feature – Return type declarations. Return type declarations specifies the what type of value that a function should return.

Following types of return types values can be declared.

  • int
  • float
  • boolean
  • string
  • interfaces
  • array
  • callable

Example of Valid Return Type –

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

//Output: 9

Example of Invalid Return Type –

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

//Output: Fatal error: Uncaught TypeError: Return value of returnIntValue() must be of the type int, float returned in...
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial