What's the "true" Standalone Type in PHP?

Starting with PHP 8.2, you can use true as a standalone type, which allows you to add typehint to the following:

  1. Class Properties;
  2. Function/method arguments;
  3. Function/method return types.

For example:

class Foo {
	private true $bar;

	// ...
}
// PHP 8.2+
function foo(true $arg) {
    // ...
}

foo(true);
// PHP 8.2+
function foo(): true {
    return true;
}

It is possible to use it to make the bool type narrower (or more specific). For example, you could do it in a :

class User {
    public function canEdit(): bool
    {
        // ...
        return $isAllowed;
    }
}

class Admin extends User
{
    public function canEdit(): true
    {
        return true;
    }
}

Please note that the true type does not allow the following:

#Coercion Is Not Allowed

The true type does not coerce values of other types to true.

For example, if you return an int 1 instead of true from a function that has the true type specified as the return type, then it will throw an error:

// PHP 8.2+
function foo(): true {
    // Fatal error: Uncaught TypeError: foo(): Return value must be of type true, int returned
    return 1;
}

foo();

#Union of bool|true Is Not Allowed

If you specify bool|true (or true|bool), PHP would throw the following compile time error:

// PHP 8.2+
// Fatal error: Duplicate type true is redundant
function foo(): bool|true {
    // ...
}

#Union of true|false Is Not Allowed

If you specify true|false (or false|true) instead of bool, PHP will throw the following compile time error:

// PHP 8.2+
// Fatal error: Type contains both true and false, bool should be used instead
function foo(): true|false {
    // ...
}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.