Search code examples
phplaravelmethods

Method overloading in Laravel even though my class is being extended


I'm trying to use BaseServiceClass and ChildServiceClass in my service. I want to make this method: makePost (PostObject $postObject){} in ChildServiceClass which extends BaseServiceClass.

In BaseServiceClass I have defined makePost as such: makePost (PostObject $postObject){}

As for PostObject it extends BaseObject but I get this error when I try to set these Objects to parent and child I get that ChildServiceClass:makePost() is not compatible with method BaseServiceClass:makePost()

Example:

In Base service:

public function addFilter(BaseSearchObject $searchObject, $query){
    return $query;
}

In ProductService:

public function addFilter(ProductSearchObject $searchObject, $query)
    {
       //code that overrites BaseController
    }

as for the search objects:

class ProductSearchObject extends BaseSearchObject

Is there a way I can pass different classes to these methods?


Solution

  • The error is very simple, you are trying to overwrite a method with PostObject that originally accepts a BaseObject.

    The fact that PostObject extends BaseObject has nothing to do here, since a PostObject is never a BaseObject, it is always more than a BaseObject, but a BaseObject can sometimes be a PostObject.

    The solution is to not use any of these objects, but have the object implement a common interface like IsServicable and have all methods accept an object that implements this interface rather than a concrete type.

    If using php8 you can also use union types. In this case you make both services accept both types of inputs.

    public function makePost(BaseObject|PostObject $object){}