Does the PHP true Type Coerce Values of Other Types?

Find out if the true type in PHP converts values of other types to true

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

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;


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;

	// ...

Hope you found this post useful. It was published . Please show your love and support by sharing this post.