Void

void 是仅用于返回类型,表示函数不返回值,但该函数仍可能会终止。因此,它不能成为联合类型声明的一部分。自 PHP 7.1.0 起可用。

注意: 即使函数的返回类型是 void,但仍然可以返回值,但值只能始终为 null

添加备注

用户贡献的备注 1 note

up
0
harl at gmail dot com
2 days ago
"Even if a function has a return type of void it will still return a value, this value is always null."

Syntactically, a void-returning function's return statements must be plain `return;`. If the function is declared as returning null then the return statement needs to include a return value: `return null;`.

A function that always returns null ("function foo(): null {...}") is equivalent to a void-returning function ("function foo(): void {...}"). Neither actually returns any information to the caller (the caller always receives null, and doesn't learn anything from it).

Meaningful return type declarations using null are always union types. "function foo(): null" is legal but pointless and might as well be written as returning void to make explicit the fact that it doesn't return anything meaningful (and indicates that "$v = foo();" is certainly a mistake of some sort.) The exception to this is if foo() is a subclass method overriding a wider-but-still-nullable type from a superclass.

(And the technical reason why a void function still returns null is that a function call is an expression so needs to have SOME value if it returns at all.)
To Top