PHP inheritance problem (7.1)

I have the following structure:

class AffiliateRepository extends GenericRepository implements IAffiliateRepository {

}


abstract class GenericRepository  {
    public function save(BaseModel $model) : int{
        $model->save();
        return $model->getId();
    }

}

interface IAffiliateRepository  {

    public function save(Affiliate $affiliate) : int;
}

public class Affiliate extends BaseModel{}


$affiliateRepository  = new AffiliateRepository();
$affiliateRepository->save(new Affiliate());

      

I expect to GenericRepository

take care of the save action.

but I am getting the following error:

Declaration of App\Services\AffiliateRepository::save(App\Models\Affiliate $affiliate): int should be compatible with App\Services\GenericRepository::save(App\Models\BaseModel $model): int

Why? Affiliate

inherited from BaseModel

.
What is the best way to overcome this and allow the GenericRepository

function call to be handled save

.

thank

+3


source to share


3 answers


Have a look at the methods:

// GenericRepository
public function save(BaseModel $model)

// IAffiliateRepository
public function save(Affiliate $affiliate) : int;

      



Both classes should expect the same type. If you contribute IAffiliateRepository

to the class GenericRepository

, it will be correct. You may also need to change the variable names to be the same.

+1


source


Seems a bit messy, but the problem is that in order AffiliateRepository

to implement the IAffiliateRepository

signature save

must be

save(Affiliate $affiliate) : int

      

The implementation in GenericRepository

does not satisfy this.



You can try this in AffiliateRepository

...

public function save(Affiliate $affiliate) : int {
    return parent::save($affiliate);
}

      

0


source


@enricog gave the correct answer in a comment: in order to satisfy an interface, a method save

must accept whatever object is BaseModel

. The method provided IAffiliateRepository

does not do this.

0


source







All Articles