首页 > 解决方案 > 如何强制子类实现其父类接口方法

问题描述

我有多个扩展父类的子类。

我想“强制”子类在每个子类中声明一个方法列表。

class childClass_A{
    function interfaceMethod(){}
}
class childClass_B{
    function interfaceMethod(){}
}
etc.

为了做到这一点,我研究了接口。

我知道我可以让所有子类实现一个特定的接口,但那不是多余的代码吗?

class childClass_A implements MyInterface{
    function interfaceMethod(){}
}
class childClass_B implements MyInterface{
    function interfaceMethod(){}
}
etc.

相反,我想到了让父类实现接口。

class parentClass implements MyInterface{
    function interfaceMethod(){}
}

class childClass_A extends parentClass{

}

但是,这样做会将声明接口方法的“义务”分配给父类,如果子类不包含接口的方法之一,则不会产生错误。

是否可以确保父对象的接口方法也在子类中声明?

标签: php

解决方案


您可以将父类声明为抽象类,也可以将所需的方法声明为抽象类。

这样,子类必须实现这些方法,就像使用接口一样,否则它们不能被实例化。

如果您需要为特定的子类重用一个或多个方法,您可以考虑在 trait 中定义它们。


推荐阅读