Skip to content

self, parent and static types are not resolved to classes when checking type variance #1025

Open

Description

@NopeCharon

BetterReflection reports self, parent and static as built-in types (ReflectionNamedType#isBuiltin() returns true for them). TypeIsCovariant and TypeIsContravariant treat every built-in type as unrelated to any class, so swapping a class name for the equivalent self/parent, or narrowing a return type to static, is reported as a BC break:

// before
class Base {}
final class Foo extends Base
{
    public function withA(): Foo { return $this; }
    public function withB(): self { return $this; }
    public function make(): object { return $this; }
    public function equals(self $other): bool { return true; }
    public function accept(Foo $other): void {}
}

// after
final class Foo extends Base
{
    public function withA(): self { return $this; }       // same type
    public function withB(): static { return $this; }     // narrower
    public function make(): static { return $this; }      // narrower
    public function equals(Foo $other): bool { return true; } // same type
    public function accept(parent $other): void {}       // wider
}
[BC] CHANGED: The return type of X\Foo#withA() changed from X\Foo to the non-covariant self
[BC] CHANGED: The return type of X\Foo#withB() changed from self to the non-covariant static
[BC] CHANGED: The parameter $other of X\Foo#equals() changed from self to a non-contravariant X\Foo
[BC] CHANGED: The parameter $other of X\Foo#accept() changed from X\Foo to a non-contravariant parent
[BC] CHANGED: The return type of X\Foo#make() changed from object to the non-covariant static
5 backwards-incompatible changes detected

None of these changes can break a caller. The same applies to property types: public Foo $foo → public self $foo in Foo is reported by PropertyTypeChanged.

ReflectionNamedType#getClass() already resolves self, parent and static to the class they refer to, so the variance checks can use it. static needs care: it may refer to any child class, so static → self is still not covariant.

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