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
source to share
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.
source to share
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);
}
source to share