php - 如何强制子类实现其父类接口方法
问题描述
我有多个扩展父类的子类。
我想“强制”子类在每个子类中声明一个方法列表。
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{
}
但是,这样做会将声明接口方法的“义务”分配给父类,如果子类不包含接口的方法之一,则不会产生错误。
是否可以确保父对象的接口方法也在子类中声明?
解决方案
您可以将父类声明为抽象类,也可以将所需的方法声明为抽象类。
这样,子类必须实现这些方法,就像使用接口一样,否则它们不能被实例化。
如果您需要为特定的子类重用一个或多个方法,您可以考虑在 trait 中定义它们。
推荐阅读
- laravel - Nova Filters - 过滤具有 belongsTo 关系的资源?
- elasticsearch - 无法在 Elasticsearch 中执行搜索,错误“嗅探集群状态失败”。
- android - 使用 PDF 库在现有 PDF 文件上绘制小图像
- java - 如何使用 Apache POI 自动调整工作表中所有列的大小
- ios - 如何使用静态方法更改属性值?
- java - 当我从 arraylist 调用时,为什么会有多个输出?
- jms - 嵌入 ActiveMQ Artemis 的 JBoss EAP 7.1 之间的远程查找失败
- java - 如何将 JSON 字符串转换为 JSON 数组列表?
- javascript - 如何在 Javascript 中自动更改页面?
- java - 如何让 WebApp 在嵌入式码头的类路径上找到应用程序属性?