Skip to content

true and false are not considered subtypes of bool when checking type variance #1024

Open

Description

@NopeCharon

Since PHP 8.0 (false) and PHP 8.2 (true), both are standalone types and subtypes of bool. Narrowing a return type from bool to false/true, or widening a parameter type from false/true to bool, is allowed by PHP's inheritance rules (https://3v4l.org can confirm):

class P { function a(): bool { return true; } function b(false $x) {} }
class C extends P { function a(): false { return false; } function b(bool $x) {} } // OK

TypeIsCovariant and TypeIsContravariant don't know about this relationship, so these changes are reported as BC breaks wherever variance is checked (final classes, final methods, functions):

// before
final class Foo
{
    public function isOk(): bool { return true; }
    public function set(false $f): void {}
}

// after
final class Foo
{
    public function isOk(): false { return false; }
    public function set(bool $f): void {}
}
[BC] CHANGED: The return type of X\Foo#isOk() changed from bool to the non-covariant false
[BC] CHANGED: The parameter $f of X\Foo#set() changed from false to a non-contravariant bool
2 backwards-incompatible changes detected

Neither change can break a caller: every value of false is a bool, and every argument accepted as false is still accepted as bool.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions