Skip to content

PHPStan incorrectly reports method.childReturnType error for generic template inheritance with $this types #13418

Description

@calebdw

Bug report

PHPStan reports method.childReturnType errors when a child class overrides methods from a generic parent class that use $this in the return type annotation, even when the inheritance is
correctly defined.

Expected Behavior

The child class method return type should be considered compatible with the parent class method return type when:

• Child extends Parent with proper generic type specification
• Method signatures are identical
• Return types are logically compatible through inheritance

Actual Behavior

PHPStan reports:

Return type (HasOne<AgreementSignature, $this(Agreement)>) of method Agreement::signature()
should be compatible with return type (HasOne<AgreementSignature, $this(AbstractContract)>)
of method AbstractContract::signature()

/** @template TSignature of AbstractSignature */
abstract class AbstractContract extends Model
{
    /**
     * Eloquent relation to the contract's signature class to return latest Signatures.
     *
     * @return HasOne<TSignature, $this>
     */
    abstract public function signature(): HasOne;
}

/** @extends AbstractContract<AgreementSignature> */
final class Agreement extends AbstractContract
{
    #[Override]
    public function signature(): HasOne
    {
		return new HasOne(AgreementSignature::class, $this);
    }
}

Code snippet that reproduces the problem

https://phpstan.org/r/0ed44220-9626-459f-9eab-b6f37da57425

Expected output

I would expect there to be no errors

Did PHPStan help you today? Did it make you happy in any way?

No response

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

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions