Overriding Interface Method Parameters: A Case of Liskov Substitution Violation
In PHP, you may encounter a situation where overriding an interface method parameter with a child interface leads to an error. Consider the following code:
<code class="php">interface Engine { function run(); } interface HydroEngine extends Engine { function run(); } interface Car { function setEngine(Engine $engine); } interface WaterCar extends Car { function setEngine(HydroEngine $engine); }</code>
Unfortunately, this code produces the error:
Fatal error: Declaration of WaterCar::setEngine() must be compatible with Car::setEngine(Engine $engine)
Reason for the Error
The error occurs because by overriding the setEngine method in the WaterCar interface, you are violating the Liskov substitution principle. This principle states that a subclass should be substitutable for its parent class without breaking the program's behavior.
The WaterCar interface, as a subclass of Car, must accept the same parameter type as the parent interface's setEngine method, which is Engine. By overriding it with HydroEngine, you are narrowing the acceptable parameter type, making WaterCar less substitutable than Car.
Solution
To resolve this issue, you must ensure that the subclasses of an interface adhere to the same parameter types as the parent interface. In this case, you should not override the setEngine method in the WaterCar interface, but instead inherit the Car interface's definition.
The above is the detailed content of Is Overriding Interface Method Parameters with Child Interfaces a Violation of Liskov Substitution Principle?. For more information, please follow other related articles on the PHP Chinese website!