English 中文(简体)
PHP 7 - Return Type Declarations
  • 时间:2024-11-03

PHP 7 - Return Type Declarations


Previous Page Next Page  

In PHP 7, a new feature, Return type declarations has been introduced. Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.

    int

    float

    bool

    string

    interfaces

    array

    callable

Example - Vapd Return Type

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

It produces the following browser output −

5

Example - Invapd Return Type

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

It produces the following browser output −

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