Does the PHP true Type Coerce Values of Other Types?

In PHP, the true type does not coerce any other type to true, no matter if the "strict_types=1" directive is declared in a script or not. This is different from the bool typehint, which does coerce scalar values.

As per the RFC, coercion might be implemented in the future for true type as well. The reason it hasn't been implemented yet is that it might impact the implementation of literal types.

Consider, for example, the following, where an int 1 is passed in instead of true:

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

// Fatal error: Uncaught TypeError: foo(): Argument #1 ($arg) must be of type true, int given
foo(1);

The same thing happens for a non-true return value when the return type is true:

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

foo();

Similarly, when a non-true value is assigned to a class property, it will throw an error too:

class Foo {
    // Fatal error: Cannot use int as default value for property Foo::$bar of type true
    private true $bar = 1;

	// ...
}

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.