PHP Reference ยท Types and Type Handling
PHP mixed, never and void types
Reference for the special PHP types mixed, void, never, static and null/true/false: what each means, where it is allowed and how they differ.
Besides ordinary types, PHP has a few special ones that describe what a function accepts or returns in unusual cases.
mixed means "any value", including null. void is a return type for functions that return nothing. never is a return type for functions that never come back: they always throw an exception or end the script. static (a return type only) means "an instance of the class the method was called on".
function log_message(string $text): void { echo $text; } function fail(string $why): never { throw new RuntimeException($why); } function pick(mixed $anything): mixed { return $anything; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
function f(mixed $x): mixed { } function g(): void { } // no value; "return;" is allowed function h(): never { } // throws or exits function i(): static { } // methods only function j(): true { } // PHP 8.2; also false and null
| Type | Meaning | Allowed as |
|---|---|---|
mixed |
Any value, including null |
parameter, return, property |
void |
Returns nothing | return type only |
never |
Never returns normally | return type only |
static |
The late-bound class | return type only |
true, false, null |
That single value | any position since 8.2 (false only in a union before) |
Usage notes
mixedis explicit. An untyped parameter also accepts anything, butmixeddocuments that you really mean it and the engine checks that you did not forget the type.mixedalready includesnull, so?mixedandmixed|nullare errors.voidreturnsnullto the caller, but you cannot writereturn null;orreturn $x;in avoidfunction, and you cannot usevoidin a union or as a parameter type.neverreplacesvoidfor exit paths. A function declarednevermust throw, callexit(), or loop forever; falling off the end throws aTypeError. Static analysers use this to know the code after the call is unreachable.staticreturn types are great for fluent builders, as in the second example.selfwould return the parent type for subclass calls.- Prefer precise types.
mixedloses all the help from the type checker. Reach for unions (int|string) or interfaces first. - Version notes:
void7.1,mixed8.0,staticreturn 8.0,never8.1, standalonenull,trueandfalse8.2.