简体   繁体   中英

PHP (7.1) inheritance issue

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 am expecting GenericRepository to take care on the save action.

but I'm 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 is that? Affiliate inherits from BaseModel .
Whats the best way to overcome that and let GenericRepository handle the save function call.

thanks

Look at methods:

// GenericRepository
public function save(BaseModel $model)

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

Both classes have to expect the same type. If you implement IAffiliateRepository into GenericRepository class, it will be correct. You may also need to change variable names to be the same.

Seems a bit messy but the problem is, in order for AffiliateRepository to implement the IAffiliateRepository , the signature of save must be

save(Affiliate $affiliate) : int

The implementation in GenericRepository does not satisfy this.

You could try this in AffiliateRepository ...

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

@enricog gave the correct answer in a comment: to satisfy the interface the save method must accept any object that is a BaseModel . The method provided by IAffiliateRepository does not do that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM