返回值类型声明
php7之前是不支持对函数返回值类型进行声明的,如下所示:
function test(string $param):array {
return 1;
}
echo test(1);
php5.6版本运行该程序,结果如下:
Parse error: syntax error, unexpected ':', expecting '{' in /data/compare/return.php on line 3
可见直接就是语法错误了
而php7中,增加了对返回值类型的声明的支持,如果返回值类型与设置的类型不匹配,将会抛出致命错误。同样php7.4版本下运行以上代码:
PHP Fatal error: Uncaught TypeError: Return value of test() must be of the type array, int returned in /data/compare/return.php:4
Stack trace:
#0 /data/compare/return.php(7): test('1')
#1 {main}
thrown in /data/compare/return.php on line 4
同时,php7新特性值标量类型声明中的标量类型声明,declare声明指令不仅影响参数的类型声明,也影响到函数的返回值声明,示例代码如下:
<?php
declare(strict_types=1); // 设置标量类型声明为严格模式
function test(int $param):string { // 声明返回值类型为string字符串类型
return 1; // 实际返回值类型为int
}
echo test(1);
以上程序将会报错:
PHP Fatal error: Uncaught TypeError: Return value of test() must be of the type string, int returned in /data/compare/return.php:4
Stack trace:
#0 /data/compare/return.php(7): test(1)
#1 {main}
thrown in /data/compare/return.php on line 4