Reputation: 11285
I've created an interface called iMapper
. And I want all my mappers file to implement that interface.
But each mapper will specify the parameter type.
Example:
interface iMapper
{
public function insert($obj);
public function update($obj);
public function delete($obj);
}
class CarMapper implements iMapper
{
public function insert(Car $obj){}
public function update(Car $obj){}
public function delete(Car $obj){}
}
That code generate the following error:
Declaration of CarMapper::insert() must be compatible with that of iMapper::insert()
Is their a way of making the interface compatible with the CarMapper
? (I don't want to change the mapper.)
Thanks
Upvotes: 4
Views: 4475
Reputation: 27
better:
interface iObject {}
class Car implements iObject
interface iMapper
{
public function insert(iObject $obj);
public function update(iObject $obj);
public function delete(iObject $obj);
}
class CarMapper implements iMapper
{
public function insert(Car $obj){}
public function update(Car $obj){}
public function delete(Car $obj){}
}
Upvotes: 1
Reputation: 9283
"But each mapper will specify the parameter type." - I have to say that can't be done.
Interface must be implemented. What does it mean? That all implementing classes will have to be able to use methods with not specified parameter - parameter that was required by method inside interface.
calling instanceof
inside method body is some kind of way out, but it's realy not a good way.
Read about strategy pattern, I bet it can solve your problem - http://sourcemaking.com/design_patterns/strategy/php
Upvotes: 3
Reputation: 20045
Your class has to implement the interface. But it doesn't so PHP complains.
You might use type checking within the methods.
Have a look at instanceof.
Upvotes: 0
Reputation: 475
interface iMapper
{
public function insert(Car $obj);
public function update(Car $obj);
public function delete(Car $obj);
}
class CarMapper implements iMapper
{
public function insert(Car $obj){}
public function update(Car $obj){}
public function delete(Car $obj){}
}
interface and class methods must match! Same type hinting must be used.
Upvotes: 0