Home >Backend Development >PHP Tutorial >Can Child Interfaces Override Interface Method Parameters with More Specific Types?
Overriding Interface Method Parameters with Child Interfaces
In the given PHP code, an attempt is made to override the setEngine method of the Car interface with a more specific parameter type in the child interface WaterCar. However, this results in a fatal error:
<code class="php">Fatal error: Declaration of WaterCar::setEngine() must be compatible with Car::setEngine(Engine $engine)</code>
Explanation of Error
The error stems from a violation of the Liskov substitution principle (LSP), which states that a subtype must be substitutable for its supertype. In this case, the WaterCar interface is a subtype of the Car interface, but the setEngine method in WaterCar has a different parameter type (HydroEngine) than the corresponding method in Car (Engine).
This creates a compatibility issue. A class that implements the WaterCar interface may not be able to be passed as an argument to functions that expect a Car object, because the setEngine method will not accept an Engine parameter. Therefore, the subclass does not fulfill all the requirements of the superclass, breaking the LSP.
Resolution
To resolve this issue, the setEngine method in the WaterCar interface should maintain compatibility with the method in the Car interface. This means preserving the same parameter type (Engine) or providing a more general type that includes Engine, such as Vehicle.
<code class="php">interface WaterCar extends Car { function setEngine(Vehicle $engine); }</code>
With this change, any class implementing WaterCar can still be used in places where a Car is expected, as it now accepts a parameter of the same or more general type.
The above is the detailed content of Can Child Interfaces Override Interface Method Parameters with More Specific Types?. For more information, please follow other related articles on the PHP Chinese website!