无涯教程-PHP - 返回类型声明

58 阅读1分钟

在PHP 7中,引入了一个新函数返回类型声明,返回类型声明指定函数应返回的值的类型,可以声明返回类型的以下类型。

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

有效返回类型

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

它产生以下浏览器输出-

5

无效返回类型

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

它产生以下浏览器输出-

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

参考链接

www.learnfk.com/php7+/php7-…