mixed, never, static, null, false and true types

suggest change

Besides int, string, class names and so on, PHP has a few special types. They don't describe a kind of value as much as a promise about it: "anything", "never returns", "the same class as the object", "always true".

Type Since Where Meaning
void 7.1 return returns nothing (the caller gets null)
static 8.0 return an instance of the class the method was called on
mixed 8.0 everywhere any value, including null
never 8.1 return the function never returns: it throws, exits or loops forever
null 8.2 standalone everywhere only null
false 8.2 standalone everywhere only false
true 8.2 everywhere only true
iterable 7.1, alias since 8.2 everywhere Traversable|array

This article goes through them one by one. All examples were run with PHP 8.5. In error messages, paths are shortened to /app/.

For combining types with |, & and parentheses see Union, intersection and DNF types. void is covered in Type hinting no return (void) and ?T in Nullable type hints.

mixed

mixed (PHP 8.0) accepts any value: int, float, string, bool, array, object, resource, callable and null. It is the same as the union array|bool|callable|int|float|null|object|resource|string.

<?php
declare(strict_types=1);

function describe(mixed $value): string
{
    return get_debug_type($value);
}

foreach ([42, 'hi', null, [1, 2], new DateTimeImmutable(), fopen('php://memory', 'r')] as $v) {
    echo describe($v), "\n";
}

Output:

int
string
null
array
DateTimeImmutable
resource (stream)

mixed vs no type at all

A parameter typed mixed accepts exactly what an untyped parameter accepts. So why write it? Because it tells the reader (and static analysers like PHPStan or Psalm) that "any value" is a decision, not a forgotten type. Coding standards that require a type on every declaration rely on it.

There are also real differences in behavior.

Typed properties have no implicit null default. An untyped property starts as null. A mixed property is a typed property, so it is uninitialized until you assign it:

<?php
class Untyped { public $value; }
class Mixed_ { public mixed $value; }

var_dump((new Untyped)->value);

try {
    var_dump((new Mixed_)->value);
} catch (Error $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

Output:

NULL
Error: Typed property Mixed_::$value must not be accessed before initialization

Write public mixed $value = null; if you want the old behavior.

A mixed return type requires an explicit return. A function without a return type that falls off its end returns null. With : mixed, every path must return something, even if it's null:

<?php
function find(array $data, string $key): mixed
{
    if (array_key_exists($key, $data)) {
        return $data[$key];
    }
}

var_dump(find(['a' => 1], 'a'));
var_dump(find(['a' => 1], 'b'));

Output:

int(1)

Fatal error: Uncaught TypeError: find(): Return value must be of type mixed, none returned in /app/m3.php:7

A bare return; is even caught at compile time:

function nothing(): mixed
{
    return; // Fatal error: A function with return type must return a value
            // (did you mean "return null;" instead of "return;"?)
}

mixed already includes null, so ?mixed and mixed|null are errors: "Type mixed cannot be marked as nullable since mixed already includes null". mixed can't be part of any union.

mixed and inheritance

mixed is the top type: every other type is a subtype of it. That fits the variance rules nicely:

<?php
interface Cache
{
    public function get(string $key): mixed;
    public function set(string $key, int|string $value): void;
}

class StringCache implements Cache
{
    private array $items = [];

    // return type narrowed from mixed to ?string (covariance)
    public function get(string $key): ?string
    {
        return $this->items[$key] ?? null;
    }

    // parameter widened from int|string to mixed (contravariance)
    public function set(string $key, mixed $value): void
    {
        $this->items[$key] = (string) $value;
    }
}

$c = new StringCache();
$c->set('answer', 42);
var_dump($c->get('answer'), $c->get('missing'));

Output:

string(2) "42"
NULL

One surprise: removing the return type in a child is not allowed once the parent says mixed. A missing return type isn't treated as mixed here:

class Base { public function get(): mixed { return 1; } }
class Child extends Base { public function get() { return 1; } }
// Fatal error: Declaration of Child::get() must be compatible with Base::get(): mixed

Use mixed when a value really can be anything: a generic container, a cache, json_decode() output, a value passed through to a callback. If you find yourself checking is_int() / is_string() right after, a union like int|string says more.

never

never (PHP 8.1) is a return type for functions that never return normally. They either throw an exception, call exit() / die(), or loop forever.

<?php
declare(strict_types=1);

function fail(string $message, int $code = 400): never
{
    throw new RuntimeException($message, $code);
}

function parseAge(string $input): int
{
    if (!ctype_digit($input)) {
        fail("not a number: '$input'");
    }
    // PHP and static analysers know we only get here for valid input
    return (int) $input;
}

foreach (['42', 'abc'] as $s) {
    try {
        echo parseAge($s), "\n";
    } catch (RuntimeException $e) {
        echo "error: ", $e->getMessage(), " (code ", $e->getCode(), ")\n";
    }
}

Output:

42
error: not a number: 'abc' (code 400)

The benefit is mostly for tools and readers. With : void, an analyser would assume fail() can return and warn that parseAge() may continue with invalid input. With : never, it knows code after the call is unreachable in the error branch.

Typical uses: error helpers, redirects and HTTP responses that end the script, and loops of long-running workers:

<?php
function redirect(string $url): never
{
    header("Location: $url");
    exit;
}

function runForever(): never
{
    $i = 0;
    while (true) {
        if (++$i === 3) {
            echo "giving up after $i tries\n";
            exit(1);
        }
        echo "try $i\n";
    }
}

runForever();

Output (exit code 1):

try 1
try 2
giving up after 3 tries

For a real-world example of a never function throwing domain exceptions see Custom errors.

never vs void

Both mean "the caller gets no useful value", but they say different things:

PHP enforces never at runtime. If the function reaches its end, you get a TypeError:

<?php
function oops(): never
{
    echo "forgot to throw\n";
}

try {
    oops();
} catch (TypeError $e) {
    echo get_class($e), ": ", $e->getMessage(), "\n";
}

Output:

forgot to throw
TypeError: oops(): never-returning function must not implicitly return

A return statement, even an empty one, is a compile-time error: "A never-returning function must not return".

Rules for never

<?php
abstract class Shape
{
    abstract public function area(): float;
}

class Unknown extends Shape
{
    // never is a subtype of every type, so it can replace any return type
    public function area(): never
    {
        throw new LogicException('area of an unknown shape');
    }
}

try {
    (new Unknown)->area();
} catch (LogicException $e) {
    echo $e->getMessage(), "\n";
}

Output:

area of an unknown shape
class A { public function stop(): never { exit; } }
class B extends A { public function stop(): void {} }
// Fatal error: Declaration of B::stop(): void must be compatible with A::stop(): never

static

static as a return type (PHP 8.0) means "an instance of the class this method was called on", which may be a subclass of the class that declares the method. It is the type-system side of Late static binding.

The classic use is a fluent API (see also Method Chaining in PHP). With : self, a method inherited from a parent class would be typed as returning the parent, and IDEs would lose track of the subclass's methods. With : static the subclass is preserved:

<?php
class QueryBuilder
{
    protected array $conditions = [];

    public function __construct(private string $table) {}

    public function where(string $condition): static
    {
        $this->conditions[] = $condition;
        return $this;
    }

    public function sql(): string
    {
        $sql = "SELECT * FROM {$this->table}";
        if ($this->conditions) {
            $sql .= ' WHERE ' . implode(' AND ', $this->conditions);
        }
        return $sql;
    }
}

class UserQuery extends QueryBuilder
{
    public function __construct()
    {
        parent::__construct('users');
    }

    public function active(): static
    {
        return $this->where('active = 1');
    }
}

// where() is declared in QueryBuilder, but here it returns a UserQuery,
// so ->active() can be chained after it
echo (new UserQuery)->where('age > 18')->active()->sql(), "\n";

Output:

SELECT * FROM users WHERE age > 18 AND active = 1

static vs self

self is resolved where the method is written, static where it is called. PHP checks the static return type at runtime against the actual class of the object:

<?php
class Base
{
    public function selfFluent(): self { return $this; }
    public function staticFluent(): static { return $this; }
    public function wrong(): static { return new Base(); }
}

class Child extends Base {}

$c = new Child();
echo get_class($c->selfFluent()), "\n";
echo get_class($c->staticFluent()), "\n";

echo get_class((new Base)->wrong()), "\n";
try {
    $c->wrong();
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

Child
Child
Base
Base::wrong(): Return value must be of type Child, Base returned

selfFluent() returns a Child too, because $this is a Child and a Child is also a Base. The difference is in the declared type: self promises only a Base. wrong() shows that a static method must not create a hardcoded new Base(); it must use $this, new static(...) or clone.

Named constructors and withers

new static(...) together with : static gives you factory methods and immutable "withers" that work for subclasses without being redefined:

<?php
class Money
{
    final public function __construct(
        public readonly int $amount,
        public readonly string $currency,
    ) {}

    public static function of(int $amount, string $currency): static
    {
        return new static($amount, $currency);
    }

    public function withAmount(int $amount): static
    {
        return new static($amount, $this->currency);
    }
}

class Price extends Money
{
    public function format(): string
    {
        return sprintf('%d.%02d %s', intdiv($this->amount, 100), $this->amount % 100, $this->currency);
    }
}

$p = Price::of(1999, 'EUR');
$discounted = $p->withAmount(1499);
echo get_class($discounted), ": ", $discounted->format(), "\n";
echo $p->format(), "\n";

Output:

Price: 14.99 EUR
19.99 EUR

The constructor is final on purpose. new static(...) calls the constructor of whatever subclass is used, so a subclass with a different constructor signature would break of() and withAmount(). Making the constructor final (or declaring it in an interface) keeps new static safe. More on withers in Immutability.

Rules for static

class P { public static function make(): static { return new static; } }
class C extends P { public static function make(): self { return new static; } }
// Fatal error: Declaration of C::make(): C must be compatible with P::make(): static

null, false and true

Before PHP 8.2, null and false could appear only as part of a union: ?Foo, string|false. PHP 8.2 allowed them as standalone types and added true, both alone and in unions.

<?php
declare(strict_types=1);

function isEnabled(): true
{
    return true;
}

function alwaysFalse(): false
{
    return false;
}

function nothingHere(): null
{
    return null;
}

var_dump(isEnabled(), alwaysFalse(), nothingHere());

function strictTrue(true $flag): string
{
    return 'ok';
}

echo strictTrue(true), "\n";
try {
    strictTrue(false);
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

Output:

bool(true)
bool(false)
NULL
ok
strictTrue(): Argument #1 ($flag) must be of type true, false given, called in /app/t1.php on line 28

When standalone types make sense

A function that always returns the same value looks odd on its own. These types are useful mainly with inheritance: a parent declares a wide type and a child narrows it, documenting that its implementation is simpler.

<?php
interface Logger
{
    public function log(string $message): ?string;
}

// a logger that never produces an id can say so precisely
class NullLogger implements Logger
{
    public function log(string $message): null
    {
        return null;
    }
}

interface Validator
{
    public function validate(mixed $value): bool;
}

class AcceptAll implements Validator
{
    public function validate(mixed $value): true
    {
        return true;
    }
}

var_dump((new NullLogger)->log('hi'), (new AcceptAll)->validate(42));

Output:

NULL
bool(true)

Code that holds a NullLogger (not just a Logger) and a static analyser can now rely on these results without checks.

true in unions is handy for functions that return "success or an error description". Before 8.2 you had to write string|bool, which wrongly allows false:

<?php
function save(string $path, string $data): string|true
{
    return file_put_contents($path, $data) === false ? "cannot write $path" : true;
}

And int|false, string|false remain common in the signatures of built-in functions like strpos(), file_get_contents() and filter_var(). In your own code, prefer ?T for "no result" (see Union, intersection and DNF types).

null vs void

null and void look alike, since in both cases the caller gets null. The differences:

Use void for "returns nothing". Use null only when narrowing a parent's ?T.

No coercion for true and false

In coercive mode (without declare(strict_types=1), see Strict typing) a bool parameter accepts 1 or 'yes' and converts them to true. A true parameter does not:

<?php
// coercive mode: no declare(strict_types=1)
function takesBool(bool $b): string { return var_export($b, true); }
function takesTrue(true $b): string { return var_export($b, true); }

foreach ([1, 'yes'] as $v) {
    echo 'bool <- ', var_export($v, true), ': ', takesBool($v), "\n";
    try {
        $r = takesTrue($v);
        echo 'true <- ', var_export($v, true), ': ', $r, "\n";
    } catch (TypeError $e) {
        echo 'true <- ', var_export($v, true), ': ', $e->getMessage(), "\n";
    }
}

Output (the "called in" part of the messages is cut):

bool <- 1: true
true <- 1: takesTrue(): Argument #1 ($b) must be of type true, int given
bool <- 'yes': true
true <- 'yes': takesTrue(): Argument #1 ($b) must be of type true, string given

Rules for null, false and true

Declaration Result
?null Fatal error: null cannot be marked as nullable
true|false Fatal error: Type contains both true and false, bool must be used instead
bool|true, bool|false Fatal error: Duplicate type true (false) is redundant
?false, null|false, null|true allowed
public null $x; allowed, but pointless

iterable is an alias for Traversable|array

iterable (PHP 7.1) accepts anything you can foreach over: arrays and objects implementing Traversable (iterators, IteratorAggregate, generators).

<?php
declare(strict_types=1);

function total(iterable $numbers): int
{
    $sum = 0;
    foreach ($numbers as $n) {
        $sum += $n;
    }
    return $sum;
}

function gen(): Generator
{
    yield 1;
    yield 2;
}

echo total([1, 2, 3]), "\n";
echo total(new ArrayIterator([4, 5])), "\n";
echo total(gen()), "\n";

$type = (new ReflectionFunction('total'))->getParameters()[0]->getType();
echo get_class($type), ": ", $type, "\n";

Output:

6
9
3
ReflectionNamedType: iterable

Since PHP 8.2, iterable is no longer a separate type but a compile-time alias for Traversable|array. In practice it works the same, with a few visible effects:

Variance follows directly from the union: a method returning iterable can be narrowed to array or Generator in a child class, and a parameter typed array can be widened to iterable.

Reflection

All these types show up in reflection as ordinary types. mixed, null and ?false allow null, the others don't:

<?php
class Demo
{
    public function a(mixed $x): never { exit; }
    public function b(): static { return $this; }
    public function c(): null { return null; }
    public function d(): ?false { return null; }
    public function e(): int|true { return true; }
    public function f(iterable $x): void {}
}

foreach ((new ReflectionClass(Demo::class))->getMethods() as $m) {
    $t = $m->getReturnType();
    printf("%s(): %-14s %-22s allowsNull=%s\n",
        $m->getName(), $t, get_class($t), var_export($t->allowsNull(), true));
}
$p = (new ReflectionMethod(Demo::class, 'a'))->getParameters()[0]->getType();
echo "a(\$x): $p, builtin=", var_export($p->isBuiltin(), true), ", allowsNull=", var_export($p->allowsNull(), true), "\n";

Output:

a(): never          ReflectionNamedType    allowsNull=false
b(): static         ReflectionNamedType    allowsNull=false
c(): null           ReflectionNamedType    allowsNull=true
d(): ?false         ReflectionNamedType    allowsNull=true
e(): int|true       ReflectionUnionType    allowsNull=false
f(): void           ReflectionNamedType    allowsNull=false
a($x): mixed, builtin=true, allowsNull=true

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents