在PHP7,一个新的功能,返回类型声明已被引入。返回类型声明指定的一个函数返回值的类型。以下类型可以用来作为返回类型声明。
- int
- float
- bool
- 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...
关注编程技巧 回复19领350本编程书籍