PHP 7.新增了返回类型声明
http://php.net/manual/en/functions.returning-values.php
在PHP 7.1中新增了返回类型声明为void,以及类型前面增加问号表示可以返回null,例如?init,不过和某些语言中的细节略有不同,没什么技术含量,就是语言的定义,直接上代码吧。
php -r "function a() : int {return 1;} var_dump(a());"
int(1)
php -r "function b() : int {return;} var_dump(b());"
Fatal error: A function with return type must return a value in Command line code on line 1
php -r "function c() : int {return null;} var_dump(c());"
Fatal error: Uncaught TypeError: Return value of c() must be of the type integer, null returned in Command line code:1
php -r "function d() : null {return 1;} var_dump(d());"
Fatal error: Cannot use 'null' as class name as it is reserved in Command line code on line 1
php -r "function e() : void {return 1;} var_dump(e());"
Fatal error: A void function must not return a value in Command line code on line 1
php -r "function f() : void {return;} var_dump(f());"
NULL
php -r "function g() : void {return null;} var_dump(g());"
Fatal error: A void function must not return a value (did you mean "return;" instead of "return null;"?) in Command line code on line 1
php -r "function h() : ?null {return 1;} var_dump(h());"
Fatal error: Cannot use 'null' as class name as it is reserved in Command line code on line 1
php -r "function i() : ?void {return 1;} var_dump(i());"
Fatal error: Void type cannot be nullable in Command line code on line 1
php -r "function j() : ?int {return 1;} var_dump(j());"
int(1)
php -r "function k() : ?int {return;} var_dump(k());"
Fatal error: A function with return type must return a value (did you mean "return null;" instead of "return;"?) in Command line code on line 1
php -r "function l() : ?int {return null;} var_dump(l());"
NULL
php -r "function m() : void {return;} function n() : ?int {return null;} var_dump(m() === n());"
bool(true)