Skip to content

Declaration of Methods should be Compatible with Parent Methods in PHP

In PHP, when a class inherits from another class, it is said to be a subclass or derived class. The subclass inherits all of the properties and methods of the parent class, but it can also add or override those methods.

When a subclass overrides a method of the parent class, it must have the same method signature. This means that the method name and the number and type of parameters must be the same. The return type can be different, but it should be compatible with the return type of the parent method. This is known as method compatibility or covariant return types. Note that prior to PHP 8.0, method signatures technically consisted only of the method name and parameters. Since PHP 8.0, return types are included in the signature, and strict compatibility checks apply.

For example, if a parent class has a method named calculate that takes two integers and returns an integer, the overriding method must accept two integers and return a value compatible with an integer.

php
class ParentClass {
    public function get(int $id): ParentClass {
        return new ParentClass();
    }
}

class ChildClass extends ParentClass {
    // Covariant return type: returning a subclass of the parent's return type
    public function get(int $id): ChildClass {
        return new ChildClass();
    }
}

Covariant return types are supported in PHP 7.0 and later. In PHP 8.0+, return types are strictly checked as part of the method signature. By following these rules, the subclass can be used interchangeably with the parent class, and the parent class' methods can be called on an object of the subclass without causing errors.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.